我有一个数据框 test_num
作为索引:
file_num 6 7
test_num
79 NaN ↑
148 ↑ NaN
我需要减少它以保持任何 file_num
的第一个可用方向(箭头) :
direction
test_num
79 ↑
148 ↑
我已经尝试过这个:
fd.agg(lambda x: [a for a in x if a][0], axis=1)
test_num
79 NaN
148 ↑
fd.agg(lambda x: [a for a in x if a != pd.np.nan][0], axis=1)
test_num
79 NaN
148 ↑
如何在这里做我需要的事情?
最佳答案
您可以在groupby
中使用统一数组
df.groupby([*'A'*len(df.columns)], 1).first()
A
test_num
79 ↑
148 ↑
<小时/>
或者使用可调用来达到相同的效果
df.groupby(lambda x: 'A', 1).first()
A
test_num
79 ↑
148 ↑
关于python - pandas:聚合以保留第一个非 NaN 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51972517/