如果不是NaN,Pandas从列中获取值

时间:2016-03-26 16:51:20

标签: python-3.x pandas

给出以下数据框:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A':['One','Two',np.nan],
                   'B':[np.nan,np.nan,'Three'],
                   })
df

    A       B
0   One     NaN
1   Two     NaN
2   NaN     Three

我想创建一个列(' C'),其中包含“A' A'或者' B'如果它不是这样的NaN:

    A       B        C
0   One     NaN      One
1   Two     NaN      Two
2   NaN     Three    Three

提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用combine_first

df['C'] = df.A.combine_first(df.B)
print df                   
     A      B      C
0  One    NaN    One
1  Two    NaN    Two
2  NaN  Three  Three

fillna

df['C']= df.A.fillna(df.B)
print df                   
     A      B      C
0  One    NaN    One
1  Two    NaN    Two
2  NaN  Three  Three

np.where如果两个条件均为假,则添加值,例如1:

df['C'] = np.where(df.A.notnull(), df.A,np.where(df.B.notnull(), df.B, 1))
print df                   
     A      B      C
0  One    NaN    One
1  Two    NaN    Two
2  NaN  Three  Three