python - 使用 Python/Pandas 清除 Dataframe 中的错误标头
问题描述
我有一个损坏的数据帧,其中数据帧内有随机标题重复。加载数据框时如何忽略或删除这些行?
由于这个随机头在数据框中,熊猫在加载时会引发错误。我想在用熊猫加载它时忽略这一行。或者在用熊猫加载它之前以某种方式删除它。
该文件如下所示:
col1, col2, col3
0, 1, 1
0, 0, 0
1, 1, 1
col1, col2, col3 <- this is the random copy of the header inside the dataframe
0, 1, 1
0, 0, 0
1, 1, 1
我想:
col1, col2, col3
0, 1, 1
0, 0, 0
1, 1, 1
0, 1, 1
0, 0, 0
1, 1, 1
解决方案
投入na_filter = False
以将您的列类型转换为字符串。然后找到所有包含错误数据的行,然后将它们过滤掉您的数据框。
>>> df = pd.read_csv('sample.csv', header = 0, na_filter = False)
>>> df
col1 col2 col3
0 0 1 1
1 0 0 0
2 1 1 1
3 col1 col2 col3
4 0 1 1
5 0 0 0
6 1 1 1
>>> type(df.iloc[0,0])
<class 'str'>
既然您已将每列中的数据解析为字符串,col1, col2, and col3
请在 df 中找到所有值,如果您在每列中找到它们,则创建一个新列np.where()
,如下所示:
>>> df['Tag'] = np.where(((df['col1'] != '0') & (df['col1'] != '1')) & ((df['col2'] != '0') & (df['col2'] != '1')) & ((df['col3'] != '0') & (df['col3'] != '1')), ['Remove'], ['Don\'t remove'])
>>> df
col1 col2 col3 Tag
0 0 1 1 Don't remove
1 0 0 0 Don't remove
2 1 1 1 Don't remove
3 col1 col2 col3 Remove
4 0 1 1 Don't remove
5 0 0 0 Don't remove
6 1 1 1 Don't remove
现在,使用 过滤掉列中标记为Removed
的那个。Tag
isin()
>>> df2 = df[~df['Tag'].isin(['Remove'])]
>>> df2
col1 col2 col3 Tag
0 0 1 1 Don't remove
1 0 0 0 Don't remove
2 1 1 1 Don't remove
4 0 1 1 Don't remove
5 0 0 0 Don't remove
6 1 1 1 Don't remove
删除Tag
列:
>>> df2 = df2[['col1', 'col2', 'col3']]
>>> df2
col1 col2 col3
0 0 1 1
1 0 0 0
2 1 1 1
4 0 1 1
5 0 0 0
6 1 1 1
最后将您的数据帧类型转换为 int,如果您需要它是整数:
>>> df2 = df2.astype(int)
>>> df2
col1 col2 col3
0 0 1 1
1 0 0 0
2 1 1 1
4 0 1 1
5 0 0 0
6 1 1 1
>>> type(df2['col1'][0])
<class 'numpy.int32'>
注意:如果您想要标准索引,请使用:
>>> df2.reset_index(inplace = True, drop = True)
>>> df2
col1 col2 col3
0 0 1 1
1 0 0 0
2 1 1 1
3 0 1 1
4 0 0 0
5 1 1 1
推荐阅读
- sql - System.Data.Entity.Core.EntityCommandExecutionException 发生无效的浮点操作
- visual-studio-2015 - 迁移到 X64 后:CComPtr CoCreateInstance 失败,rc=0x80040154 类未注册
- c# - 友好的数字对
- asp.net-mvc - 在 mvc 5 中验证日期时间
- reactjs - 如何通过点击子标签获得“价值”?
- jquery - Wordpress Contact From7 默认选择当天
- html - 如何使用纯 CSS 为切换类上的边框设置动画?
- java - 无法使用 Maven 构建项目
- 3d - Onirix Targets 播放器应用程序中的 3D 模型质量不佳
- r - 仅时间转换(小时和分钟)