尝试将 csv 文件读入我的数据类型时出现值错误。我需要确保它有效并且每一行都被读入并且是正确的。
错误例如:
Pandas: ValueError: Integer column has NA values in column 2
Run Code Online (Sandbox Code Playgroud)
我试图在 Pandas Python 库中转换为整数,但有一个值。
但是,我读入的 csv 文件似乎有一些错误的条目,因为它由手动输入的测试结果组成。
我读到使用这个命令:
test = pd.read_csv("test.csv", sep=";", names=pandasframe_names, dtype=pandasframe_datatypes, skiprows=1)
Run Code Online (Sandbox Code Playgroud)
名称为 A、B、C、D 和 E,并且定义正确。
如果有错误的条目,我需要一种处理此问题而不丢失整行的方法。
这是我的情况:我有一个 pandas 数据框,它读取 csv 表,该表有 5 列,标题为 A、B、C、D、E。我使用参数skiprows=1 跳过第一行
pandas_datatypes={'A': pd.np.int64, 'B':pd.np.int64, 'C':pd.np.float64, 'D':object, 'E':object}
Run Code Online (Sandbox Code Playgroud)
我的行有 5 列,前 2 列是 int64,第三列是 float64,接下来的 2 列是对象(例如字符串)
当我读入它时,这些相当于我的数据类型。含义dtype=pandas_datatypes
现在我有这样的条目:
entry 1: 5; 5; 2.2; pedagogy; teacher (correct)
entry 2: 8; 7.0; 2.2; pedagogy; teacher (incorrect, as second is float instead of int)
entry 3: NA; 5; 2.2; pedagogy; teacher (incorrect, as first value has entered NA as is missing)
entry 4: none; 5; 2.2; pedagogy; teacher (incorrect, as first value has entered none as is missing)
entry 5: 8; 5; 2; pedagogy; teacher (incorrect, as third is int instead of float)
Run Code Online (Sandbox Code Playgroud)
我该如何最好地处理这个问题以及我必须添加什么才能确保这项工作正常进行?万一有一个错误的输入,我不想丢失整行。我应该输入 NULL 吗?但随后我需要标记此内容以便有人手动查看它。
Eti*_*nne 25
Pandas 现在有扩展类型,其中整数支持 NA 值。您将在这些字段中获得 pd.NA。
https://pandas.pydata.org/docs/user_guide/basics.html#basics-dtypes
使用 Pandas Int64 类型,就可以了!
pandas_datatypes={'A': 'Int64', 'B': 'Int64', 'C':pd.np.float64, 'D':object, 'E':object}
Run Code Online (Sandbox Code Playgroud)
刚刚用 pandas 1.3.5 进行了测试,效果非常好。
由于您的数据不完整/损坏(很常见!),因此您无法从一开始就强制执行数据类型。您必须首先按原样导入它:
鉴于file1.csv:
5; 5; 2.2; pedagogy; teacher
8; 7.0; 2.2; pedagogy; teacher
NA; 5; 2.2; pedagogy; teacher
none; 5; 2.2; pedagogy; teacher
8; 5; 2; pedagogy; teacher
Run Code Online (Sandbox Code Playgroud)
我们可以将其读作
df = pd.read_csv('file1.csv', sep=';', header=None, names=['A', 'B', 'C', 'D', 'E'])
Run Code Online (Sandbox Code Playgroud)
然后,我们将 A、B 和 C 强制转换为数字,强制NaN存在文本的地方。
for col in ['A', 'B', 'C']:
df[col] = pd.to_numeric(df[col], errors='coerce')
Run Code Online (Sandbox Code Playgroud)
然后你将 C 作为浮点列。将 A 和 B 转换为整数有点棘手,因为它们具有NaN值(一个已知的 Pandas 问题)。
如果您的分数为 0.24 或更高,您可以执行以下操作:
df['A'] = df['A'].astype(pd.Int64Dtype())
df['B'] = df['B'].astype(pd.Int64Dtype())
Run Code Online (Sandbox Code Playgroud)
否则,您可以NaN以某种方式填充 s,或者使用浮动。
| 归档时间: |
|
| 查看次数: |
27076 次 |
| 最近记录: |