如何将 pandas 数据框中的多列从字符串转换为整数?

Blu*_*ail 0 python dataframe pandas

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

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
Run Code Online (Sandbox Code Playgroud)

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

我努力了

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

df_all['1981'] = df_all['1981'].astype('int64')
Run Code Online (Sandbox Code Playgroud)

这导致了 ValueError: invalidliteral 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'>
Run Code Online (Sandbox Code Playgroud)

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

另外,有没有办法使用 cols=df_all.loc[:, '1981':'2019'] 一次将它们全部转换?

Anu*_*bas 5

尝试使用replace():

df_all['1981'] = df_all['1981'].replace(',','',regex=True)
Run Code Online (Sandbox Code Playgroud)

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

df_all['1981'] = df_all['1981'].astype('int64')
Run Code Online (Sandbox Code Playgroud)

如果你想转换多列,那么:

df[df.columns[2:]]=df[df.columns[2:]].replace(',','',regex=True).astype('int64')
Run Code Online (Sandbox Code Playgroud)