pandas CSV使用'-'作为NULL,将列转换为INT时出错

h43kikqp  于 2022-12-10  发布在  其他
关注(0)|答案(1)|浏览(107)

我有CSV

df = pd.read_csv('data.csv')

表格:
| A列|B栏|C列|
| - -|- -|- -|
| 小行星4068744| -1472525年|小行星2596|
| 小行星198366|- -|- -|
文件正在使用'-'表示nul值
我试着转换成int,但不行程那个'-'。
我的问题是:我如何去掉字符串'-'而不改变负值?

df['Column B'] = df['Column B'].astype(int)

ValueError:基数为10的int()的文字无效:'-'

yquaqz18

yquaqz181#

pandas的更高版本可以容纳缺少值的integer dtype。普通int转换不支持空值。

# replace - with null
df.replace('-', pd.NA, inplace=True)
# and use Int surrounding with ''
df['Column B'] = df['Column B'].astype('Int64')

输出:

> df

  Column A  Column B Column C
0  4068744  -1472525  2596219
1   198366      <NA>     <NA>

> df['Column B'].info

Name: Column B, dtype: Int64>

相关问题