python - 如何替换熊猫数据框中包含括号或数字的列中的那些条目?
问题描述
I have a dataframe like this:
Country Energy Supply Energy Supply per Capita
16 Afghanistan 3.210000e+08 10.0
17 Albania 1.020000e+08 35.0
18 Algeria 1.959000e+09 51.0
19 American Samoa NaN
40 Bolivia
(Plurinational State of) 3.360000e+08 32.0
... ... ... ...
213 Switzerland17 1.113000e+09 136.0
214 Syrian Arab Republic 5.420000e+08 28.0
215 Tajikistan 1.060000e+08 13.0
216 Thailand 5.336000e+09 79.0
228 Ukraine18 4.844000e+09 107.0
232 United States of
America20 9.083800e+10 286.0
我需要替换名称中带有括号或数字的所有国家/地区的名称。例如:“Bolivia (Plurinational State of)”应为“Bolivia”,“Switzerland17”应为“Switzerland”,“United States of America20”应为“United States of America”。我使用 replace() 和 split() 尝试了这个,但对我来说没有任何效果。
有人可以帮我解决这个问题。
解决方案
regex
您可以像这样使用多个str.replace
:
考虑以下数据框:
In [1431]: df
Out[1431]:
Country
0 Afghanistan
1 Bolivia (Plurinational State of)
2 Switzerland17
In [1433]: df['Country'] = df['Country'].str.replace(r"\(.*\)|\d+",'')
In [1434]: df
Out[1434]:
Country
0 Afghanistan
1 Bolivia
2 Switzerland
推荐阅读
- javascript - HTML5 Canvas ctx.fill() 填充描边区域外
- java - 将 eclipse paho mqtt 依赖项添加到 Andrdoid Studio 项目时出现重复类错误
- java - 在 GET 方法中过滤对象的可选属性
- php - Spatie Browsershot 和信头 / CSS
- node.js - 尝试使用 ioredis nodejs 模块使用密码连接到哨兵时出错
- php - PHP/MYSQL - 返回变量匹配数据点的列名
- reactjs - 奇怪使用 React 无状态组件
- haskell - 在 Haskell 的实践中使用递归类型与带有递归方案的参数化类型
- c - 链表地址
- javascript - 将函数的结果(返回)作为 ReactJS 中的 Prop 传递