【问题标题】:Parsing an irregularly spaced text file in Python pandas在 Python pandas 中解析不规则间距的文本文件
【发布时间】:2016-09-22 00:29:38
【问题描述】:

我有一个看起来像这样的文本文件:

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

我想对其进行解析以将不规则空格删除为格式良好的 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

【问题讨论】:

  • 我尝试使用 akafruit.split() 的 split() 方法,但无法使用数据框执行此操作,但我可以使用简单的字符串执行此操作,例如 'aug-6 apple green 4'
  • 请编辑您的问题并提供您的编码实现的minimal reproducible example,以帮助更好地说明您的实现问题。
  • @user3609179 那你的问题不是解决了吗?您只需要打开文件并遍历调用split 然后join 将它们与逗号分隔符一起返回的每一行。对于字符串s','.join(s.split())

标签: python pandas


【解决方案1】:

如果您可以使用命令行工具,则可以运行此awk 命令将其从空格分隔变为逗号分隔。

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

否则,pandas 可以轻松导入空格分隔的文件。

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

【讨论】:

  • 如何在 ubuntu 的终端上保存 awk 生成的结果
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 2011-08-29
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    相关资源
    最近更新 更多