如何在熊猫数据框中将多列从字符串转换为整数?

时间:2021-05-11 14:38:11

标签: python pandas dataframe

我有一个包含多个年份列的数据框。

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

我想将年份列(1981 年到 2020 年)的数据从“object”转换为“int64”。

我试过了

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

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

导致 ValueError: invalid literal for int() with base 10: '5,180'

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

所以我不知道为什么它甚至对单列也不起作用?

另外,有没有办法一次使用 cols=df_all.loc[:, '1981':'2019']?

1 个答案:

答案 0 :(得分:2)

尝试使用 replace()

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

现在尝试使用 astype() 方法:

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

如果要转换多列,则:

df[df.columns[2:]]=df[df.columns[2:]].replace(',','',regex=True).astype('int64')