这是我的数据帧
import pandas as pd
data = [[1, 1, 1, 0],
[1, 2, 1, 1],
[1, 2, 2, 2],
[2, 1, 1, 3]]
df = pd.DataFrame(data, columns=["idx 1", "idx 2", "idx 3", "value"])
>>> df
idx 1 idx 2 idx 3 value
0 1 1 1 0
1 1 2 1 1
2 1 2 2 2
3 2 1 1 3
我创建了一个";三明治";函数,它复制第一行和最后一行并将它们插入第一个和最后一个位置:
def sandwich(df):
return pd.concat([df[:1], df, df[-1:]])
>>> df.apply(sandwich)
idx 1 idx 2 idx 3 value
0 1 1 1 0 # new
0 1 1 1 0
1 1 2 1 1
2 1 2 2 2
3 2 1 1 3
3 2 1 1 3 # new
当我想先对数据帧进行分组,然后将三明治函数应用于每个组时,就会出现问题。
>>> df.groupby(["idx 1", "idx 2"]).apply(sandwich)
idx 1 idx 2 idx 3 value
idx 1 idx 2
1 1 0 1 1 1 0
0 1 1 1 0
0 1 1 1 0
2 1 1 2 1 1
1 1 2 1 1
2 1 2 2 2
2 1 2 2 2
2 1 3 2 1 1 3
3 2 1 1 3
3 2 1 1 3
结果是正确的,但我实际上得到了两次,因为panda添加了一个索引,而没有删除";idx 1";以及";idx2";列。之后我可以删除索引以获得所需的结果:
>>> df.groupby(["idx 1", "idx 2"]).apply(sandwich).reset_index(drop=True)
idx 1 idx 2 idx 3 value
0 1 1 1 0
1 1 1 1 0
2 1 1 1 0
3 1 2 1 1
4 1 2 1 1
5 1 2 2 2
6 1 2 2 2
7 2 1 1 3
8 2 1 1 3
9 2 1 1 3
然而,创建一个索引以立即销毁它似乎不是最好的方法。有更好的方法吗?
在groupby
:中使用group_key=False
df.groupby(["idx 1", "idx 2"], group_keys=False).apply(sandwich)
您将维护sandwich
:生成的原始索引
idx 1 idx 2 idx 3 value
0 1 1 1 0
0 1 1 1 0
0 1 1 1 0
1 1 2 1 1
1 1 2 1 1
2 1 2 2 2
2 1 2 2 2
3 2 1 1 3
3 2 1 1 3
3 2 1 1 3