首页 > 解决方案 > 列内的字符串操作(熊猫):拆分、替换、连接

问题描述

我想根据以下条件创建一个新列:

数据样本如下:

Animal 

22 dogs
1 dog
1 cat
3 dogs
32 chats

到目前为止。

我想输出一个只有数字(数字)的列:

Animal        New column

22 dogs       22-00
1 dog         1-00
1 cat         00-1
3 dogs        3-00
32 chats      00-32

我想我应该使用一个if条件来检查单词,然后.split.join。这是关于字符串操作的,但我无法解决这个问题。

标签: pythonpandasstring

解决方案


您可以这样做,首先提取数字,然后用于np.where有条件地向字符串添加字符:

df['New Col'] = df['Animal'].str.extract(r'([0-9]*)')
df['New Col'] = np.where(df['Animal'].str.contains('dogs|dog|chiens|chien'), df['New Col']+'-00', df['New Col'])
df['New Col'] = np.where(df['Animal'].str.contains('cats|cat|chat|chats'), '00-'+df['New Col'], df['New Col'])
print(df)

     Animal New Col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32

推荐阅读