大写pandas中的字符串列

时间:2018-05-28 07:41:28

标签: python string pandas dataframe

如何以最简单的方式替换多个版本?

这是我的数据:

No  Device
1   asus
2   Xiaomi
3   xiaomi
4   Asus
5   Samsung

我想成功:

No  Device
1   Asus
2   Xiaomi
3   Xiaomi
4   Asus
5   Samsung

我做的是:

f = {'xiaomi':'Xiaomi', 'asus':'Asus'}
df['Device'] = df['Device'].map(f)

但结果是:

No  Device
1   Asus
2   NaN
3   Xiaomi
4   NaN
5   NaN

3 个答案:

答案 0 :(得分:5)

为什么不选择str.title

df['Device'] = df.Device.str.title()  
df

   No   Device
0   1     Asus
1   2   Xiaomi
2   3   Xiaomi
3   4     Asus
4   5  Samsung

这种方式不需要任何映射或字典。

答案 1 :(得分:3)

您需要的不是映射,而是replacing

df['Device'] = df['Device'].replace(f)

0       Asus
1     Xiaomi
2     Xiaomi
3       Asus
4    Samsung
Name: Device, dtype: object

​

答案 2 :(得分:2)

如果需要SELECT ID FROM YOUR_TABLE GROUP BY ID HAVING SUM(VALUE='D')>=1 AND SUM(VALUE='B')=0; dictionary,请添加fillnacombine_first

map

或者:

df['Device'] = df['Device'].map(f).fillna(df['Device'])

如果只需要首字母大写,则只使用str.capitalize

df['Device'] = df['Device'].map(f).combine_first(df['Device'])