Converting string to int in Pandas column

1284 views python

I have a .csv with US Congress biographical data that I read as a Panda df:

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

I want to convert the data in the 'Congress' column to an integer. Right now, I am first converting it to a simpler string:

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

This is successful. But, I am then trying to convert that simpler string to an integer:

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

I am getting an error:

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

Please help me resolve this error and simplify my code.

answered question

1 Answer


You need to call pd.numeric like this:

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')

posted this

Have an answer?


Please login first before posting an answer.