在Pandas列中将字符串转换为int

时间:2018-11-04 15:40:30

标签: python pandas

我有一个带https://github.com/JedWatson/classnames#usage-with-reactjs的.csv,我将其读为熊猫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)'

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

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'

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

2 个答案:

答案 0 :(得分:1)

您需要像这样致电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')

答案 1 :(得分:-1)

另一种实现方法。如果列中只有数字,则可以使用:-

 df['Congress'] = df['Congress'].astype(int)