欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Pandas获取符合条件的行、获得对应索引,及模拟Excel中的VLOOKUP功能

程序员文章站 2022-07-12 13:54:16
...

(作者:陈玓玏)

使用的原始数据集如下:

import pandas as pd

arr = pd.read_excel('C:/Users/cdl/Desktop/空值test_1.xlsx',encoding='gbk')
print(arr)
print(arr.dtypes)

结果:

numTest   timeTest strTest
0      1.0 2017-08-10     one
1      2.0 2018-08-10     two
2      NaN 2019-08-10     NaN
3      3.0        NaT   three
4      NaN        NaT    four
5      4.0 2020-08-10     NaN

numTest            float64
timeTest    datetime64[ns]
strTest             object
dtype: object

获取符合条件的行:
以下的代码是获取DataFrame中numTest列的值大于2的行内容

arr1 = arr[arr['numTest']>2]
print(arr1)

结果:

numTest   timeTest strTest
3      3.0        NaT   three
5      4.0 2020-08-10     NaN

如果想要获取哪几行符合条件,也就是获取符合条件的行的索引值,操作如下:

result = arr[arr['numTest']>2].index.tolist()
print(result)

结果:

[3, 5]

如果想要获取符合条件的行的其他列,也就是相当于Excel中VLOOKUP的功能,可以考虑把要取的行设为索引,如下:

#将timeTest列设为索引
arr = arr.set_index("timeTest")  
print(arr)
#获取对应行索引
result = arr[arr['numTest']>2].index.tolist()
print(arr1)
print(result)

结果:

                numTest strTest
timeTest                   
2017-08-10      1.0     one
2018-08-10      2.0     two
2019-08-10      NaN     NaN
NaT             3.0   three
NaT             NaN    four
2020-08-10      4.0     NaN

   numTest   timeTest strTest
3      3.0        NaT   three
5      4.0 2020-08-10     NaN

[NaT, Timestamp('2020-08-10 00:00:00')]

也可以不改变索引,直接获取过滤后的DataFrame中的特定列:

arr1 = arr[arr['numTest']>2]['timeTest']
print(arr1)

结果:

3          NaT
5   2020-08-10
Name: timeTest, dtype: datetime64[ns]
相关标签: Pandas Python