python - 转换 pandas 数据框中包含 nan、连字符和逗号的列的数据类型

标签 python pandas

df = pd.read_csv("data.csv", encoding = "ISO-8859-1")

现在,我有一列值如下:

供引用的示例数据:

enter image description here

现在,我想使用以下代码将列 a 转换为数字格式:

df[['A']] = df[['A']].astype(int)

它给了我一个错误。 问题是我将所有三个(nan、连字符和逗号)都放在一栏中,需要一起解决。 有没有更好的方法来转换这些而不用替换(nan 到 -1)和类似的东西?

最佳答案

使用参数 thousandsna_values,但是对于缺失值无法转换为整数,因为现在至少有一个 NaN 值转换列到 float,参见 this .所以可能的解决方案是将它们替换为 int,例如-1 然后转换为整数:

注意 - 在新版本的 pandas(0.24.0,即将推出)中,pandas 已经获得了保存具有缺失值的整数数据类型的能力,Nullable Integer Data Type .

import pandas as pd

temp=u'''A
2254
"1,234"
"3,385"
nan
-
-
nan'''
#after testing replace 'pd.compat.StringIO(temp)' to 'data.csv'
df = pd.read_csv(pd.compat.StringIO(temp), 
                 encoding = "ISO-8859-1", 
                 thousands=',', 
                 na_values='-')

print (df)
        A
0  2254.0
1  1234.0
2  3385.0
3     NaN
4     NaN
5     NaN
6     NaN

df['A'] = df['A'].fillna(-1).astype(int)
print (df)
      A
0  2254
1  1234
2  3385
3    -1
4    -1
5    -1
6    -1

关于python - 转换 pandas 数据框中包含 nan、连字符和逗号的列的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54194584/

相关文章:

python - 执行 python 脚本后额外的零

python - 基于 yield 的协程是真正的协程吗?

python - 检查时间是否在特定分钟内的最佳方法是什么?

python - 使用其中一列中的值索引 Pandas 数据框

python - pandas 读取 excel 结果为 "not a zip file"

python - 使用多个字典创建 JSON,Python

python - 如何在 Nose2 中运行特定测试

python - 使用索引在 Pandas 中查找两个系列之间的交集

python - 在 csv 导入 pandas 期间跳过行

python - 在python中将1*5的列表(对象?)转换为df