假设我有以下数据帧:
0 1 2
1 10/1/2016 'stringvalue' 456
2 NaN 'anothersting' NaN
3 NaN 'and another ' NaN
4 11/1/2016 'more strings' 943
5 NaN 'stringstring' NaN
我想创建一个基于条件的新列“Full Entry”。 如果df[2]的值是NaN,那么df['Full Entry']也应该是NaN。你知道吗
如果df[2]!=NaN df['Full Entry']应取df[1]的值。 我想每行重复一遍。你知道吗
我想出了以下代码
df['Full_Entry'] = [df[1] if pd.isnull(x) == False else np.NaN for x in df[2]]
但这给了我以下结果
0 1 2 Full_Entry:
1 10/1/2016 'stringvalue' 456 0 stringv...
2 NaN 'anothersting' NaN NaN
3 NaN 'and another ' NaN NaN
4 11/1/2016 'more strings' 943 0 stringv...
5 NaN 'stringstring' NaN NaN
但我想要的是:
0 1 2 Full_Entry:
1 10/1/2016 'stringvalue' 456 stringvalue
2 NaN 'anothersting' NaN NaN
3 NaN 'and another ' NaN NaN
4 11/1/2016 'more strings' 943 more strings
5 NaN 'stringstring' NaN NaN
我的代码中的“if”条件似乎在正确的时刻触发,但只使用第一行的值。出于某种原因,还包括“0”。你知道吗
有人知道我的代码有什么问题吗?你知道吗
也可以使用
apply
函数:输出:
选项1
pd.Series.mask
或者
选项2
pd.Series.where
-使用^{} :
df['Full_Entry']=np.where(pd.isnull(df.2), np.NaN, df.1)
相关问题 更多 >
编程相关推荐