合并列并删除NaNs Pandas [英] Combining columns and removing NaNs Pandas
本文介绍了合并列并删除NaNs Pandas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个像这样的熊猫数据框:
If I have a pandas dataframe like so:
a1 0.116667 NaN NaN
a2 NaN 0.516667 NaN
a3 NaN 0.006667 NaN
a4 NaN NaN 0.426667
a5 NaN 0.506667 NaN
a6 0.583333 NaN NaN
a7 0.550000 NaN NaN
我想合并这些列,以便如果任何列中有一个数字,而其他两列中有NaN,则结果是一个列,其预期输出为:
and I want to combine the columns so that if there is a number in any of the columns and NaN in the other two the result is one column, with the expected output:
a1 0.116667
a2 0.516667
a3 0.006667
a4 0.426667
a5 0.506667
a6 0.583333
a7 0.550000
推荐答案
对于某些行,如果有两个或多个不是NaN
的值,则您没有指定应该怎么办.
You didn't specify what should happen if, for some row, there are two or more values that are not NaN
s.
在这种情况下,根据您的需要,一个简单的按行最大值可能会解决您的问题:
Subject to what you want in this case, a simple row-wise maximum might solve your problem:
df = pd.DataFrame({
'a': [1, None, None],
'b': [None, 3, None],
'c': [None, None, 4]})
>>> df
a b c
0 1 NaN NaN
1 NaN 3 NaN
2 NaN NaN 4
现在,取逐行最大值:
>>> df.max(axis=1)
0 1
1 3
2 4
dtype: float64
这篇关于合并列并删除NaNs Pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文