簡體   English   中英

在Python熊貓中解析不規則間距的文本文件

[英]Parsing an irregularly spaced text file in Python pandas

我有一個文本文件,看起來像:

Date     Fruit-type  Color         count
aug-6     apple  green         4
aug-7     pear  brown         5
aug-3     peach  yellow         10
aug-29     orange  orange         34

我想解析它,以將不規則空間刪除為格式正確的熊貓數據框。 我以為要刪除空格,並用另一個定界符替換它們,但無法弄清楚邏輯。

所需的輸出

Date,Fruit-type,Color,count
aug-6,apple,green,4
aug-7,pear,brown,5
aug-3,peach,yellow,10
aug-29,orange,orange,34

如果可以使用命令行工具,則可以運行此awk命令以將其從空格分隔為逗號分隔。

awk '{for (i=1; i<NF; i++){printf "%s,", $i} print $NF}' data.txt

否則,大熊貓可以輕松導入以空格分隔的文件。

import pandas as pd

frame = pd.read_table('data.txt', sep='\s+')

使用data.txt作為:

Date     Fruit-type  Color         count
aug-6     apple  green         4
aug-7     pear  brown         5
aug-3     peach  yellow         10
aug-29     orange  orange         34

輸出是

     Date Fruit-type   Color  count
0   aug-6      apple   green      4
1   aug-7       pear   brown      5
2   aug-3      peach  yellow     10
3  aug-29     orange  orange     34

您可以在此處了解更多信息: http : //pandas.pydata.org/pandas-docs/stable/io.html#csv-text-files

gawk '{gsub(/[[:blank:]]+/, ",")}1' file

Date,Fruit-type,Color,count
aug-6,apple,green,4
aug-7,pear,brown,5
aug-3,peach,yellow,10
aug-29,orange,orange,34

暫無
暫無

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

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