总结两列熊猫数据框而忽略NaN

时间:2020-07-24 13:39:33

标签: python-3.x pandas

我有一个熊猫数据框,如下所示:

 <!--  Common style for entries  -->
<Style x:Key="EntryStyle" TargetType="Entry">
    <Setter Property="PlaceholderColor" Value="{StaticResource EntryPlaceholderColor}" />
    <Setter Property="BackgroundColor" Value="Transparent" />
    <Setter Property="TextColor" Value="{DynamicResource Gray-White}" />
    <Setter Property="FontSize" Value="16" />
    <Setter Property="Margin" Value="15,0" />
    <Setter Property="HeightRequest" Value="40" />
    <Setter Property="VerticalOptions" Value="CenterAndExpand" />
    <Setter Property="ReturnType" Value="Done" />
</Style>

我想创建一列“ new”作为sum(col1,col2),而仅当列之一为Nan时才忽略Nan, 如果两个列均具有NaN值,则应返回NaN,如下所示:

我尝试了下面的代码,它工作正常。只需一行代码,有什么方法可以实现相同的目的。

import pandas as pd
df = pd.DataFrame({'ORDER':["A", "A"], 'col1':[np.nan, np.nan], 'col2':[np.nan, 5]})
df

    ORDER   col1    col2
0    A      NaN     NaN
1    A      NaN     5.0

3 个答案:

答案 0 :(得分:3)

summin_count

df['new'] = df[['col1','col2']].sum(axis=1,min_count=1)
Out[78]: 
0    NaN
1    5.0
dtype: float64

答案 1 :(得分:3)

在两列上使用add函数,该函数带有一个fill_value参数,可让您替换NaN

df['col1'].add(df['col2'], fill_value=0) 

0    NaN
1    5.0
dtype: float64

答案 2 :(得分:0)

可以吗?

df['new'] = df[['col1', 'col2']].sum(axis = 1).replace(0,np.nan)