2017-09-15 22 views
0

我期待來連接兩列在一起,如果他們不爲NaN,就像這樣:灌裝NaN的列,如果另一列是不是NaN的W /字符串連接

if(df[pd.notnull([df["Col1"]])] and df[pd.notnull([df["Col2"]])]): 
    df["Col3"] = df["Col1"] + df["Col2"] 

如果這兩列的非NULL/NaN,將另外兩個字符串放在一起並放入第3列。

我該如何去做這件事? pd.notnull的行爲並不像我期望的那樣。

我希望它的行爲是這樣的:

"First Name" "Last Name" "Full Name" 
a   b   a b 
a1   b1   a1 b1 
a2   b2   a2 b2 

其中,前格式化將會有楠「全名」列。

這是該數據將如何格式化前:

"First Name" "Last Name" "Full Name" 
a   b   NaN 
a1   b1   NaN 
a2   b2   NaN 
NaN   NaN   a3 b3 
+0

我試圖從這些帖子沒有利用 - 實現邏輯,所以我想我會問一個更一般的組合學題。 – Derp

+0

@Sam See更新了[answer](https://stackoverflow.com/a/46244516/4909087)。 –

+0

您是否確認其中一個答案可解決您的問題?如果你能[接受最有用的](https://stackoverflow.com/help/someone-answers),那將會很好。 –

回答

3

使用.loc設置Col3

In [383]: df 
Out[383]: 
    Col1 Col2 
0 a h 
1 NaN i 
2 c j 
3 NaN NaN 
4 NaN l 
5 f m 
6 g NaN 

In [384]: df.loc[df[['Col1', 'Col2']].notnull().all(1), 'Col3'] = df.Col1 + df.Col2 

In [385]: df 
Out[385]: 
    Col1 Col2 Col3 
0 a h ah 
1 NaN i NaN 
2 c j cj 
3 NaN NaN NaN 
4 NaN l NaN 
5 f m fm 
6 g NaN NaN 

詳細

In [386]: df[['Col1', 'Col2']].notnull().all(1) 
Out[386]: 
0  True 
1 False 
2  True 
3 False 
4 False 
5  True 
6 False 
dtype: bool 
+0

很好的回答! OOV – piRSquared

2
df['Full Name'].fillna(df['First Name'].str.cat(df['Last Name'], sep=' ')) 

0  a b 
1 a1 b1 
2 a2 b2 
3 a3 b3 
Name: Full Name, dtype: objec 

在地方與pd.DataFrame.update

df.update(
    df['Full Name'].fillna(df['First Name'].str.cat(df['Last Name'], sep=' ') 
) 

df 

    First Name Last Name Full Name 
0   a   b  a b 
1   a1  b1  a1 b1 
2   a2  b2  a2 b2 
3  NaN  NaN  a3 b3 

製作副本

df.assign(**{ 
    'Full Name': 
     df['Full Name'].fillna(df['First Name'].str.cat(df['Last Name'], sep=' ')) 
}) 

    First Name Last Name Full Name 
0   a   b  a b 
1   a1  b1  a1 b1 
2   a2  b2  a2 b2 
3  NaN  NaN  a3 b3 
相關問題