python-3.x - 去掉 '$' 和 ',' 的数字不会从 str 转换为 int
问题描述
我对 Python 很陌生,但对获取表格、抓取表格然后运行计算很感兴趣。我从 Wikipedia 获取了一个收入表,去掉了带有美元符号和逗号数字的列(例如,从 26,400 美元到 26400 美元),然后尝试将它们转换为整数并根据值设置条件。虽然在更新的数据框中显示的金额没有“$”或“,”,但每当我引用单个条目或列时,我仍然会得到一个带有“$”和“,”的金额。
这是代码-如果我应该将块分开更多,请道歉-这是我的第一篇文章:
import requests
import pandas as pd
from bs4 import BeautifulSoup
URL = "https://en.wikipedia.org/wiki/List_of_Maine_locations_by_per_capita_income"
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
all_tables = soup.find_all('table', class_="wikitable")
A = []
B = []
C = []
D = []
E = []
F = []
G = []
for row in all_tables[0].findAll('tr'):
cells = row.findAll('td')
if len(cells) == 7:
A.append(cells[0].text.strip())
B.append(cells[1].text.strip())
C.append(cells[2].text.strip())
D.append(cells[3].text.strip())
E.append(cells[4].text.strip())
F.append(cells[5].text.strip())
G.append(cells[6].text.strip())
df = pd.DataFrame(A,columns=['Rank'])
df['County']=B
df['Per capita income']=C
df['Median household income']=D
df['Median family income']=E
df['Population']=F
df['Number of households']=G
df
在这一点上,我删除了所有“$”和“,”的列 C 到 E。以 C 列为例。
df['Per capita income'] = df['Per capita income'].str.replace(',', '')
df['Per capita income'] = df['Per capita income'].str.replace('$', '')
然后我尝试将值(无逗号和美元符号)从“str”转换为“int”。
df['Per capita income'] = df['Per capita income'].astype(int)
虽然更改在数据框中正确显示,但对任何单元格的任何引用仍会产生带有美元符号和逗号的“str”。
我假设我在某处遗漏了一步,因为我尝试了一些将“str”转换为“int”的方法。
解决方案
这将根据您在评论中的疑问起作用。
import pandas as pd
from bs4 import BeautifulSoup
URL = "https://en.wikipedia.org/wiki/List_of_Maine_locations_by_per_capita_income"
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
all_tables = soup.find_all('table', class_="wikitable")
A = []
B = []
C = []
D = []
E = []
F = []
G = []
for row in all_tables[0].findAll('tr'):
cells = row.findAll('td')
if len(cells) == 7:
A.append(cells[0].text.strip())
B.append(cells[1].text.strip())
C.append(int(cells[2].text.strip().replace('$', '').replace(',', '')))
D.append(cells[3].text.strip())
E.append(cells[4].text.strip())
F.append(cells[5].text.strip())
G.append(cells[6].text.strip())
df = pd.DataFrame(A,columns=['Rank'])
df['County']=B
df['Per capita income']=C
df['Median household income']=D
df['Median family income']=E
df['Population']=F
df['Number of households']=G
df
推荐阅读
- android - 如何为工具栏设置我自己的菜单和返回图标?
- sql - 基于前一行结果的递归公式
- java - 无法通过 Tomcat 进行 FTP XML 下载
- javascript - 在网格中查找下一个有效单元格
- python - 为什么这个 python 代码似乎用相同的数字序列填充所有列表条目?
- html - 我在 AWS S3 上托管了简单的 HTML CSS 页面作为网站,但在实时网页上,文本“-”中的任何地方都显示为“â^”字符。我
- json - 如何通过在flutter中从json文件中获取来通过url播放视频
- sql - 如何在 Postgres 的 xml 列中索引元素的名称
- php - ParameterNotFound:缺少对在 DoctrineMongoDBBundle 中使用 staticphp 作为映射类型的依赖
- excel - 用特定值填充空白单元格超过 100,000 行