我正在清理我的熊猫数据框中的数据,我希望有比我的更好的方法来做到这一点。我在我的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循环,要么就是更聪明的东西...
谢谢您抽时间见我。
发布于 2021-11-25 16:41:40
关于从值中剔除不需要的符号的解决方案,您可以使用内置的re模块来收集字符串中的所有数字,并只获得其中最低的一个:
import re
min(map(int, re.findall(r'[0-9]+', value)))要只支持python操作,你可以尝试内置的eval函数,但是如果你需要支持不同的操作,比如'and‘来求和,你可能需要编写一个解析器来进行更多的定制。This是一篇很酷的文章,你可以查看解析器以及它们的组成部分。
编辑:
要将其应用于整个列,请提取最小数字的函数,然后应用该函数。
import re
def get_min_number(value):
return min(map(int, re.findall(r'[0-9]+', value)))
df['Count'].apply(get_min_number)https://stackoverflow.com/questions/70114296
复制相似问题