使用 Pandas 将 CSV 读入具有不同行长的数据帧 [英] Read CSV into a dataFrame with varying row lengths using Pandas
问题描述
所以我有一个看起来像这样的 CSV:
So I have a CSV that looks a bit like this:
1 | 01-01-2019 | 724
2 | 01-01-2019 | 233 | 436
3 | 01-01-2019 | 345
4 | 01-01-2019 | 803 | 933 | 943 | 923 | 954
5 | 01-01-2019 | 454
...
当我尝试使用以下代码生成数据帧时..
And when I try to use the following code to generate a dataFrame..
df = pd.read_csv('data.csv', header=0, engine='c', error_bad_lines=False)
它只将 3 列的行添加到 df(上面的第 1、3 和 5 行)
It only adds rows with 3 columns to the df (rows 1, 3 and 5 from above)
其余的被认为是坏行"给我以下错误:
The rest are considered 'bad lines' giving me the following error:
Skipping line 17467: expected 3 fields, saw 9
如何在我的 csv 中创建一个包含所有数据的数据框,可能只是用 null 填充空单元格?或者我是否必须在添加到 df 之前声明最大行长度?
How do I create a data frame that includes all data in my csv, possibly just filling in the empty cells with null? Or do I have to declare the max row length prior to adding to the df?
谢谢!
推荐答案
如果只使用pandas
,则按行读取,处理后的分隔符.
If using only pandas
, read in lines, deal with the separator after.
import pandas as pd
df = pd.read_csv('data.csv', header=None, sep='
')
df = df[0].str.split('s|s', expand=True)
0 1 2 3 4 5 6
0 1 01-01-2019 724 None None None None
1 2 01-01-2019 233 436 None None None
2 3 01-01-2019 345 None None None None
3 4 01-01-2019 803 933 943 923 954
4 5 01-01-2019 454 None None None None
这篇关于使用 Pandas 将 CSV 读入具有不同行长的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!