我有一个类似于以下(但更长)的数据框,其中某些行包含None值:
data = {'first Column': ['she is', 'they are',NaN,'we are',NaN],
'second Column ': ['my', 'her',NaN,'his',NaN],
'third column': ['friend', 'brothers',NaN,'sisters',NaN]
}
df = pd.DataFrame (data, columns = ['first Column','second Column','third column])
my_list = ['金','银','青铜']
如果不包含任何值,我想用列表替换“第三列”中的每一行,例如:
desired output:
first column second column third column
0 she is my ['gold','silver','bronze']
1 they are her ['gold','silver','bronze']
2 NaN NaN NaN
3 we are his ['gold','silver','bronze']
4 NaN NaN NaN
我尝试了np.where,但是它没有选择所需的行
np.where(df.loc[df['third column'] != 'NaN', [','.join(my_list)], df['third column']
答案 0 :(得分:2)
df.loc[df['third column'].notna(),'third column']=[my_list]
结果:
first Column second Column third column
0 she is my [gold, silver, bronze]
1 they are her [gold, silver, bronze]
2 NaN NaN NaN
3 we are his [gold, silver, bronze]
4 NaN NaN NaN
PS:如果您将data
指定为具有列名的字典,则在数据帧构造函数中不需要columns
参数。