gpt4 book ai didi

python - 将 Pandas 列中的字符串转换为 int

转载 作者:太空宇宙 更新时间:2023-11-03 21:37:41 24 4
gpt4 key购买 nike

我有一个 .csv 文件 US Congress biographical data我作为 Panda df 读到的:

df = pd.read_csv('congress100.csv', delimiter = ';', names = ['Name', 'Position', 'Party', 'State', 'Congress'], header = 0)

我的数据框如下所示:

0                   'ACKERMAN, Gary Leonard'        'Representative'    'Democrat'  'NY'  '100(1987-1988)'
1 'ADAMS, Brockman (Brock)' 'Senator' 'Democrat' 'WA' '100(1987-1988)'
2 'AKAKA, Daniel Kahikina' 'Representative' 'Democrat' 'HI' '100(1987-1988)'
3 'ALEXANDER, William Vollie (Bill), Jr.' 'Representative' 'Democrat' 'AR' '100(1987-1988)'
4 'ANDERSON, Glenn Malcolm' 'Representative' 'Democrat' 'CA' '100(1987-1988)'
5 'ANDREWS, Michael Allen' 'Representative' 'Democrat' 'TX' '100(1987-1988)'
6 'ANNUNZIO, Frank' 'Representative' 'Democrat' 'IL' '100(1987-1988)'
7 'ANTHONY, Beryl Franklin, Jr.' 'Representative' 'Democrat' 'AR' '100(1987-1988)'
8 'APPLEGATE, Douglas Earl' 'Representative' 'Democrat' 'OH' '100(1987-1988)'
9 'ARCHER, William Reynolds, Jr.' 'Representative' 'Republican' 'TX' '100(1987-1988)'
10 'ARMEY, Richard Keith' 'Representative' 'Republican' 'TX' '100(1987-1988)'

我想将“Congress”列中的数据转换为整数。现在,我首先将其转换为更简单的字符串:

df['Congress'] = df['Congress'].str.replace(r'100\(1987-1988\)', '1987')

这样就成功了。但是,我随后尝试将更简单的字符串转换为整数:

df['Congress'] = df['Congress'].pd.to_numeric(errors='ignore')

我收到错误:

AttributeError: 'Series' object has no attribute 'pd'

请帮助我解决此错误并简化我的代码。

最佳答案

您需要调用pd.numeric像这样:

import pandas as pd

df = pd.DataFrame(data=[str(i + 1980) for i in range(10)], columns=['Congress'])
df['Congress'] = pd.to_numeric(df['Congress'], errors='ignore')
print(df)

上面的代码是一个玩具示例,您只需更改您的行:

df['Congress'] = df['Congress'].pd.to_numeric(errors='ignore')

至:

df['Congress'] = pd.to_numeric(df['Congress'], errors='ignore')

关于python - 将 Pandas 列中的字符串转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53142450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com