python - 在 Pandas 中按组回填列

标签 python pandas dataframe

我有一个像

A,B,C,D
1,2,,
1,2,30,100
1,2,40,100
4,5,,
4,5,60,200
4,5,70,200
8,9,,

在第 1 行和第 4 行中,缺少 C 值( NaN )。我想分别从第 2 行和第 5 行获取它们的值。 (第一次出现相同的 A、B 值)。

如果没有找到匹配的行,只需输入 0(如最后一行)
预期操作:
A,B,C,D
1,2,30,
1,2,30,100
1,2,40,100
4,5,60,
4,5,60,200
4,5,70,200
8,9,0,

使用 fillna我找到了 bfill: use NEXT valid observation to fill gapNEXT必须从逻辑上进行观察(查看 col A、B 值),而不仅仅是即将到来的 C 列值

最佳答案

您必须调用 df.groupbyAB先然后申请bfill功能:

In [501]: df.C = df.groupby(['A', 'B']).apply(lambda x: x.C.bfill()).reset_index(drop=True)

In [502]: df
Out[502]: 
   A  B   C      D
0  1  2  30    NaN
1  1  2  30  100.0
2  1  2  40  100.0
3  4  5  60    NaN
4  4  5  60  200.0
5  4  5  70  200.0
6  8  9   0    NaN

您也可以分组然后调用dfGroupBy.bfill直接(我认为这会更快):
In [508]: df.C = df.groupby(['A', 'B']).C.bfill().fillna(0).astype(int); df
Out[508]: 
   A  B   C      D
0  1  2  30    NaN
1  1  2  30  100.0
2  1  2  40  100.0
3  4  5  60    NaN
4  4  5  60  200.0
5  4  5  70  200.0
6  8  9   0    NaN

如果你想摆脱 NaN s 在 D ,你可以这样做:
df.D.fillna('', inplace=True)

关于python - 在 Pandas 中按组回填列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45837490/

相关文章:

python - Pandas - 匹配引用号以查找最早的日期

pandas dataframe 按特定列中的值序列过滤

python - 如何在使用西里尔文(俄语)字母时解决 UnicodeEncodeError?

python - 如何过滤QComboBox的数据

python - 重新分配 Pandas df 中的列值

excel - 通过 pd.read_excel() 将 excel 工作表读取为多索引数据框

python - pandas.rpy.common.load_data() 用法/文档?

循环中的 R 动态数据框名称

python - 计算 df pandas 中所有列的扩展平均值

python - 导入错误 : cannot import name 'texttospeech' from 'google.cloud' (unknown location)