1

I have a dataframe which has multiple year columns with data.

df_all = pd.read_csv('../filename.csv', header=2, skiprows= range(38,120), 
                     encoding = "ISO-8859-1")

    Code    Persons    1981    1982        1983      1984        1985 ....
    S002    Angus      5,180   46,650      5,568     265,708     344,500

I want to convert the data for the year columns (1981 to 2020) from 'object' to 'int64'.

I have tried

df_all['1981'] = df_all['1981'].apply(np.int64)

df_all['1981'] = df_all['1981'].astype('int64')

which led to ValueError: invalid literal for int() with base 10: '5,180'

and

int(df_all['1981'])
TypeError: cannot convert the series to <class 'int'>

float(int(df_all['1981'])
TypeError: cannot convert the series to <class 'float'>

so I dont know why it does not work even for a single column?

Also, is there there a way to convert them all at once using cols=df_all.loc[:, '1981':'2019']?

2
  • What do you understand from that first ValueError? Commented May 11, 2021 at 14:54
  • FYI if you load your dataframe using the "thousands" parameter, you won't have to convert those columns at all (they'll be correctly detected as int64 in the first place): pd.read_csv('filename.csv', thousands=',') Commented Apr 9, 2024 at 14:58

1 Answer 1

6

Try with replace():

df_all['1981'] = df_all['1981'].replace(',','',regex=True)

Now try with astype() method:

df_all['1981'] = df_all['1981'].astype('int64')

If you want to convert multiple columns then:

df[df.columns[2:]]=df[df.columns[2:]].replace(',','',regex=True).astype('int64')
Sign up to request clarification or add additional context in comments.

2 Comments

I wonder if somebody advises if I can set it via skiprows= ?
If you will use skip rows parameter of read_csv() method then you lose your data and it isn't necessary that the error arises in particular top n rows and bottom n rows

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.