python - 列内的字符串操作(熊猫):拆分、替换、连接
问题描述
我想根据以下条件创建一个新列:
- 如果该行包含dogs/dog/chien/chiens,则添加-00
- 如果该行包含猫/猫/聊天/聊天,则添加 00-
数据样本如下:
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
。这是关于字符串操作的,但我无法解决这个问题。
解决方案
您可以这样做,首先提取数字,然后用于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
推荐阅读
- javascript - 打印时在 Chrome 中隐藏垂直滚动条
- contactless-smartcard - 如何确定应用于非接触式交易的 CVM 方法
- javascript - 如何正确访问和连接 vue-good-table 中的数据
- html - 将 C++ 字符串放入 HTML 代码中以在网络服务器上显示值
- flutter - 将默认构建目标从 Flutter for web 更改为 flutter for Android
- python - 在主线程中启用事件循环的情况下使用子进程调用时的文件描述符错误
- visual-studio-mac - Visual Studio Mac 扩展 mpack 失败
- tsql - 如何生成报告以显示员工缺勤的次数
- c# - 当我绘制图表时,ChartPlotter 内存增加并且从不减少
- odata - DPC_EXT 中的变更集开始/结束方法,但 GCS_METHODS-CHANGESET_BEGIN 未知