Python 基于缺失数据合并两个熊猫系列

Python 基于缺失数据合并两个熊猫系列,python,pandas,merge,Python,Pandas,Merge,如果我有: col1 col2 0 1 np.nan 1 2 np.nan 2 np.nan 3 4 np.nan 4 我如何有效地达到: col1 col2 col3 0 1 np.nan 1 1 2 np.nan 2 2 np.nan 3 3 4 np.nan 4 4 我

如果我有:

    col1       col2
0   1          np.nan
1   2          np.nan
2   np.nan     3
4   np.nan     4
我如何有效地达到:

    col1       col2     col3
0   1          np.nan   1
1   2          np.nan   2
2   np.nan     3        3
4   np.nan     4        4
我目前的解决办法是:

test = pd.Series([1,2,np.nan, np.nan])

test2 = pd.Series([np.nan, np.nan, 3,4])

temp_df = pd.concat([test, test2], axis = 1)


init_cols = list(temp_df.columns)

temp_df['test3'] = ""

for col in init_cols:
    temp_df.ix[temp_df[col].fillna("") != "", 'test3'] = list(temp_df.ix[temp_df[col].fillna("") != "", col])

理想情况下,我希望避免使用循环

这取决于在每列都有非空值的情况下要执行的操作

先取
col1
,然后用
col2

df['col3'] = df.col1.fillna(df.col2)
df['col3'] = df.col2.fillna(df.col1)
先取
col2
,然后用
col1

df['col3'] = df.col1.fillna(df.col2)
df['col3'] = df.col2.fillna(df.col1)
将重叠平均化

对重叠部分求和


你想要
df['col3']=df.sum(axis=1)
谢谢你这么做,我没想到fillna会这么做!