簡體   English   中英

pandas - 讀取非結構化 csv 並將其保存在 dataframe

[英]pandas - read unstructured csv and save it in dataframe

我有一個非結構化的 CSV,它沒有所有行的列數一致。

輸入 CSV 如下所示:

Row1,Col11,Col12,Col13
Row2,Col21,Col22,Col23,Col24,Col25
Row3,Col31,Col32
Row4,,,,Col44

請注意,這是逗號分隔的文件,很少有行甚至可能只有逗號來表示空值(例如第 4 行),但很少有可能有較少的值,其他值必須考慮空值(例如行的 rest )

我希望它按原樣將此原始文件讀入 pandas dataframe 中,如果是 Null,則放入 NaN。

像這樣的東西:

     0        1        2        3        4        5
0    Row1     Col11    Col12    Col13    NaN      NaN
1    Row2     Col21    Col22    Col23    Col24    Col25
2    Row3     Col31    Col32    NaN      NaN      NaN
3    Row4     NaN      NaN      NaN      Col44    NaN

我正在使用 pandas.read_csv function 來閱讀此內容,但看起來它使用第一行來確定列數,並且由於它不一致,因此會出錯。

代碼:

df= pd.read_csv(path, engine='python',  header = None)

錯誤:

Expected 4 fields in line 2, saw 6

我怎樣才能解決這個問題?

這樣的事情會有所幫助:

with open('out.txt') as f:
    df = pd.DataFrame([line.strip().split(',') for line in f.readlines()]
                     ).replace('', None).fillna(np.nan)

Output:

      0      1      2      3      4      5
0  Row1  Col11  Col12  Col13    NaN    NaN
1  Row2  Col21  Col22  Col23  Col24  Col25
2  Row3  Col31  Col32    NaN    NaN    NaN
3  Row4  Col31  Col32    NaN  Col44    NaN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM