首页 > 解决方案 > 去掉 '$' 和 ',' 的数字不会从 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”的方法。

标签: python-3.xstringpandasinteger

解决方案


这将根据您在评论中的疑问起作用。

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

推荐阅读