【遇见Pandas】不常用的数据选择方式

128 阅读3分钟

引文

在使用Pandas做数据选择的时候, 常用方法是loc和iloc。除此之外,还有不少好用的选择方式。本期文章,我们一起来研究下。此外,最后的一个复杂例子,也可以看看。

正文

.at/.iat

如果想在数据中获取一个具体的值,就像在平面直角坐标系中取一个点一样,可以使用.at[]

.atloc相似,它只获取一个特定的值,格式为df.at[<索引>,<列名>]

如果是一个序列,可以直接输入索引,获取该索引的值。

df.at[4, 'Q1'] # 65
df.set_index('name').at['Ben', 'Q1'] # 21 索引是name
df.at[0, 'name'] # 'Liver'
df.loc[0].at['name'] # 'Liver'
# 指定列的值对应其他列的值
df.set_index('name').at['Eorge', 'team'] # 'C'
df.set_index('name').team.at['Eorge'] # 'C'
# 指定列的对应索引的值
df.team.at[3] # 'C'

iloc只支持数字索引

df.iat[4, 2] # 65
df.loc[0].iat[1] # 'E'

类字典操作 - .get

.get方法可以类似于字典操作,它在找不到值时会返回预设的默认值(例如:0)。格式为df.get(key, default=None)

如果是DataFrame,则需要输入列名作为key,会返回该列的序列;

如果是Series,则需要输入索引,返回的是一个定值。

df.get('name', 0) # 是name列
df.get('nameXXX', 0) # 0,返回默认值
s.get(3, 0) # 93,Series传索引返回具体值
df.name.get(99, 0) # 'Ben'

.truncate

.truncate()方法可以截取DataFrame和Series的数据。可以通过将索引传入before和after参数来剔除这个区间以外的数据。例如:df.truncate(before="2022-01-01", after="2022-12-31") 将会剔除日期在 2022年1月1日 到 2022年12月31日 之外的数据。

df.truncate(before=2, after=4)
'''
name team Q1 Q2 Q3 Q4
2 Ack A 57 60 18 84
3 Eorge C 93 96 71 78
4 Oah D 65 49 61 86
'''
s.truncate(before=2, after=4)
'''
0 89
1 36
2 57
3 93
4 65
Name: Q1, dtype: int64
'''

索引选择器

pd.IndexSlice是一种Pandas中的索引选择器,它专门用于在多层索引中进行数据选择。它的使用方法类似于df.loc[]切片的方法,主要应用于在使用链式方法时,指定选择的数据的范围(通过:subset参数)。

例如:在一个具有多层索引的DataFrame中,使用df.loc[pd.IndexSlice[:, "2022-01-01":"2022-12-31"], :] 可以选取所有行,并且只选择日期在 2022年1月1日 到 2022年12月31日 这个范围内的列。

import pandas as pd

data = {'year': [2021, 2022, 2023, 2021, 2022, 2023], 
        'month': [1, 2, 3, 4, 5, 6], 
        'value': [100, 200, 300, 400, 500, 600]}
df = pd.DataFrame(data)
df = df.set_index(['year', 'month'])
df.loc[pd.IndexSlice[2021, :], :]

结果:

           value
year month       
2021 1        100
     4        400
2022 2        200
     5        500
2023 3        300
     6        600

复杂案例

import pandas as pd

# 创建一个DataFrame
teams = ['A', 'B', 'A', 'C', 'B']
names = ['John', 'Jane', 'Jim', 'Jake', 'Jill']
Q1_scores = [91, 80, 92, 88, 95]
Q2_scores = [85, 94, 88, 92, 95]
df = pd.DataFrame({'team': teams, 'name': names, 'Q1': Q1_scores, 'Q2': Q2_scores})

# 定义样式函数
def style_fun(val):
    color = 'green' if val == 'John' else 'red'
    return 'color: %s' % color

# 创建复杂条件选择器
selected = df.loc[(df.team=='A') & (df.Q1>90)]
idxs = pd.IndexSlice[selected.index, 'name']

# 应用选择器
df.loc[idxs]

# 选择这部分区域加样式
df.style.applymap(style_fun, subset=idxs)

image.png

参考文献

《深入浅出Pandas:利用Python进行数据处理与分析》

《Pandas文档》

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 7 天,点击查看活动详情