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

标签 python pandas dataframe nan

一列有 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/

相关文章:

python - 为列中包含的值过滤数据框

python - 旋转 Pandas 数据框

pandas - 如何为 Pandas 图中的每条线绘制水平线?

pandas - 对 python pandas 数据框中的多个变量进行逆透视

python - 具有多个参数的 Pandas .apply() 函数

python - pretty-print 整个 Pandas Series/DataFrame

python - 为列表的最后一项运行不同的函数

python - 如何使用 Plotly 绘制 IBM Watson NLU API JSON 输出?

python - 继承修改一个 `Meta`类

Python换行符打印两次