获取以下测试数据帧:
test_df = pd.DataFrame({'col_a' : [np.nan, np.nan, 4.0, 5.0, 12.0, 45.0, 86.0, 92.0, np.nan, np.nan, np.nan]})
test_df
col_a
0 NaN
1 NaN
2 4.0
3 5.0
4 12.0
5 45.0
6 86.0
7 92.0
8 NaN
9 NaN
10 NaN
现在我想用值0.0填充
col_a
中的所有NAs,直到第一个数据点(4.0)。我还想将最新数据点(92.0)中的所有NAs替换为100.0。
把fillna方法的关键字
value
和method
组合起来似乎并不像我最初希望的那样有效。你能帮忙吗?越是蟒蛇,越好。谢谢您。
++++++++
编辑
实际上,我可以从填充数据框的顶部开始,如下所示:
test_df.loc[0:test_df['col_a'].first_valid_index()] = test_df.loc[0:test_df['col_a'].first_valid_index()].fillna(value=0)
然后使用
fillna
方法替换NAs left,但是它非常难看,并且很难处理无数列和其他dataframe约束。++++++++
最佳答案
根据cumsum
创建的max的cumsum
创建的帮助程序序列分配值,然后通过比较min
和max
创建掩码,但是对于max,对于省略最后一个非shift
值必须NaN
:
a = test_df['col_a'].notnull().cumsum()
print (a)
0 0
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 6
9 6
10 6
Name: col_a, dtype: int32
test_df[a == a.min()] = 0
test_df[a.shift() == a.max()] = 100
print (test_df)
col_a
0 0.0
1 0.0
2 4.0
3 5.0
4 12.0
5 45.0
6 86.0
7 92.0
8 100.0
9 100.0
10 100.0
关于python - 使用给定值将pandas DataFrame填充到第一个数据点和最后一个数据点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48640509/