gpt4 book ai didi

python-3.x - 如果不是 NaN,Pandas 从列中获取值

转载 作者:行者123 更新时间:2023-12-02 04:11:55 25 4
gpt4 key购买 nike

给定以下数据框:

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'),如果它不是这样的 NaN,则采用 'A' 或 'B' 的值:

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

提前致谢!

最佳答案

您可以使用 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如果两个条件都为假,则增加值(value),例如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

关于python-3.x - 如果不是 NaN,Pandas 从列中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36238035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com