我知道如何使用apply或np.where基于另一列的值创建新列,但是有选择地更改现有列的值的方法正在逃避我; 我怀疑df.ix是参与?我接近了吗?
例如,这是一个简单的数据帧(我的数据行有数万行).如果名称以字母'e'结尾,我想更改'flag'列中的值(假设为'Blue'):
>>> import pandas as pd
>>> df = pd.DataFrame({'name':['Mick', 'John', 'Christine', 'Stevie', 'Lindsey'], \
'flag':['Purple', 'Red', nan, nan, nan]})[['name', 'flag']]
>>> print df
name flag
0 Mick Purple
1 John Red
2 Christine NaN
3 Stevie NaN
4 Lindsey NaN
[5 rows x 2 columns]
Run Code Online (Sandbox Code Playgroud)
我可以根据我的标准制作一个布尔系列:
>boolean_result = df.name.str.contains('e$')
>print boolean_result
0 False
1 False
2 True
3 True
4 False
Name: name, dtype: bool
Run Code Online (Sandbox Code Playgroud)
我只需要关键步骤来获得以下结果:
>>> print result_wanted
name flag
0 Mick Purple
1 John Red
2 Christine Blue
3 Stevie Blue
4 Lindsey NaN
Run Code Online (Sandbox Code Playgroud)
U2E*_*EF1 12
df['flag'][df.name.str.contains('e$')] = 'Blue'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10949 次 |
| 最近记录: |