例如,我有一个包含名称和颜色的水果数据集。如何根据我选择的水果名称更改颜色列中的值?
Name Color
Apple NaN
Pear Green
Pear Green
Banana Yellow
Watermelon Green
我有一个粗略的想法,但我不知道如何编码。
df[Name] == Apple then df[color] == Red
答案 0 :(得分:2)
一种方法是使用.apply():
In [83]: df
Out[83]:
Name Color
0 Apple NaN
1 Pear Green
2 Pear Green
3 Banana Yellow
4 Watermelon Green
In [84]: df['Color'] = df.apply(lambda x: 'Red' if x.Name == 'Apple' else x.Color, 1)
In [85]: df
Out[85]:
Name Color
0 Apple Red
1 Pear Green
2 Pear Green
3 Banana Yellow
4 Watermelon Green
另一种更简单的方法是使用.ix:
In [94]: df
Out[94]:
Name Color
0 Apple NaN
1 Pear Green
2 Pear Green
3 Banana Yellow
4 Watermelon Green
In [95]: df.ix[df.Name == 'Apple', 'Color'] = 'Red'
In [96]: df
Out[96]:
Name Color
0 Apple Red
1 Pear Green
2 Pear Green
3 Banana Yellow
4 Watermelon Green