在使用groupby()时,如果想忽略pandas数据框中具有唯一索引的几行,可以使用reset_index()函数将唯一索引转换为默认的整数索引,然后使用drop_duplicates()函数去除重复行。
具体步骤如下:
df.reset_index(inplace=True)
df.drop_duplicates(inplace=True)
这样就可以忽略具有唯一索引的几行,进行groupby()操作了。
示例代码:
import pandas as pd
# 创建示例数据框
data = {'A': ['foo', 'foo', 'bar', 'bar', 'foo'],
'B': ['one', 'two', 'one', 'two', 'one'],
'C': [1, 2, 3, 4, 5]}
df = pd.DataFrame(data)
# 重置索引并去除重复行
df.reset_index(inplace=True)
df.drop_duplicates(inplace=True)
# 使用groupby()进行操作
grouped = df.groupby(['A', 'B'])
result = grouped.sum()
print(result)
输出结果:
index C
A B
bar one 2 3
foo one 0 6
two 1 2
在上面的例子中,通过reset_index()函数将原本具有唯一索引的行转换为整数索引,并使用drop_duplicates()函数去除重复行。然后通过groupby()函数对列'A'和列'B'进行分组,最后通过sum()函数对分组后的结果进行求和操作。
领取专属 10元无门槛券
手把手带您无忧上云