【发布时间】:2022-01-03 22:01:57
【问题描述】:
我正在清理我的 pandas 数据框中的数据,我希望有比我更好的方法来做到这一点。 我在我的 pandas dateframe 输入中的列 ["count"] 中,就像他的:
~186-205
4 and 4
200
800-1000
550-550[2]
10, 20 or 50
5 (four score and bla bla)
38 or 30
88-80
如果有人能告诉我如何将数字相加,如果他们说“x 和 x”,那就太好了。 但是,我的主要目标只是从每一行中获得最低的数字,而其他一切都消失了。
我的解决方案几乎完全成功:
df['Count'] = df['Count'].str.replace(r"\(.*\)","") #all square brackets with content
df['Count'] = df['Count'].str.replace(r"\[.*\]","") #all square brackets with content
df['Count'] = df['Count'].str.replace("(−).*","") #For one type of hyphens
df['Count'] = df['Count'].str.replace("(-).*","") #for another type of hyphens
df['Count'] = df['Count'].str.replace("(—).*","") #for yet another type of hyphens
df['Count'] = df['Count'].str.replace("(\u2013).*","") #because of different formating for hyphens
df['Count'] = df['Count'].str.replace("(or).*","") #for other alternatives, remove
df['Count'] = df['Count'].str.replace("(,).*","") #everything after commas
df['Count'] = df['Count'].replace(r'\D+', "", regex=True) #everything but numbers
有什么建议可以让这更优雅吗? 无论是在函数中、for 循环中还是更智能的东西中......
感谢您的宝贵时间。
【问题讨论】:
标签: python pandas data-cleaning