【发布时间】:2021-03-20 09:21:43
【问题描述】:
我从这个 URL 抓取了这张表:
“https://www.patriotsoftware.com/blog/accounting/average-cost-living-by-state/”
看起来像这样:
State Annual Mean Wage (All Occupations) Median Monthly Rent Value of a Dollar
0 Alabama $44,930 $998 $1.15
1 Alaska $59,290 $1,748 $0.95
2 Arizona $50,930 $1,356 $1.04
3 Arkansas $42,690 $953 $1.15
4 California $61,290 $2,518 $0.87
然后我写了这个函数来帮助我把字符串变成整数:
def money_string_to_int(s):
return int(s.replace(",", "").replace("$",""))
money_string_to_int("$1,23")
当我将它应用于一列时,我的函数有效。我在这里找到了关于在多个列上使用的答案:How to apply a function to multiple columns in Pandas
但是我下面的代码不起作用并且没有产生错误:
ls = ['Annual Mean Wage (All Occupations)', 'Median Monthly Rent',
'Value of a Dollar']
ppe_table[ls] = ppe_table[ls].apply(money_string_to_int)
【问题讨论】:
-
您只需要在
s中使用.str,然后再使用replace。 -
在它给我这个错误之前我已经这样做了:'str' object has no attribute 'str'