gpt4 book ai didi

python - 合并 Pandas 中包含 NaN 的相邻列

转载 作者:太空宇宙 更新时间:2023-11-04 08:38:44 25 4
gpt4 key购买 nike

一列有 NaN 和一些值,其他列也有 NaN 和一些值。不可能两列都有值,但两列都有 NaN 是可能的。有没有办法可以将列合并在一起?我试过用 forumla 选择一列和 df.fillna,但这不起作用。

quad_data['new'] = quad_data.apply(lambda x: function(x.a, x.b, const_a, const_b), axis=1)
df1 = pd.merge(df1, quad_data[['a','b','new']], left_on=['a','b'], right_on = ['a','b'], how='inner')


new_x new_y
0 NaN 0.997652
1 NaN 0.861592
2 0 NaN
3 0.997652 NaN
4 0.861592 NaN
5 2.673742 NaN
6 2.618845 NaN
7 NaN 0.432525
8 NaN NaN
9 0.582576 NaN
10 0.50845 NaN
11 NaN 0.341510
12 NaN 0.351510
13 1.404787 NaN
14 2.410116 NaN
15 0.540265 NaN
16 NaN 1.404787
17 NaN 2.410116
18 NaN 0.540265
19 NaN 1.403903
20 1.448987 NaN

最佳答案

combine_firstfillna 通常是不错的替代方案,但这些替代方案有效,因为您的 NaN 是互斥的。

选项 1
df.max

s = quad_data.max(1)
print(s)
0 0.997652
1 0.861592
2 0.000000
3 0.997652
4 0.861592
5 2.673742
6 2.618845
7 0.432525
8 NaN
9 0.582576
10 0.508450
11 0.341510
12 0.351510
13 1.404787
14 2.410116
15 0.540265
16 1.404787
17 2.410116
18 0.540265
19 1.403903
20 1.448987
dtype: float64

选项 2
df.sum

s = quad_data.sum(1)
print(s)
0 0.997652
1 0.861592
2 0.000000
3 0.997652
4 0.861592
5 2.673742
6 2.618845
7 0.432525
8 NaN
9 0.582576
10 0.508450
11 0.341510
12 0.351510
13 1.404787
14 2.410116
15 0.540265
16 1.404787
17 2.410116
18 0.540265
19 1.403903
20 1.448987
dtype: float64

quad_data['new'] = s 

关于python - 合并 Pandas 中包含 NaN 的相邻列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com