简体   繁体   English

使用 pandas 将文本文件列转换为 csv 文件单行?

[英]convert text file column into csv file single row using pandas?

I have text file which look like this: txt file我有如下所示的文本文件: txt 文件

Now I want to convert that text file in csv file single row现在我想在 csv 文件单行中转换该文本文件

The outcome would look like: output结果看起来像: output

This is my code:这是我的代码:

with open("file.txt", "r") as fin,\
     open("file.csv", "w") as fout:
    col1, col2,col3,col4 = zip(*(line.rstrip().split() for line in fin))
    fout.write(",".join(col1 + col2 +col4 +col5))

textfile:文本文件:

 data1 data5 data9 data13 data2 data10 data14 data data7 data11 data15 data4 data12 data16 1 5 9 13 2 10 14 3 7 11 15 4 12 16 output: data1 data2 data3 data4 data5 data7 data10 data11.... data16 1 2 3 4 5 7 10 11.... 16

Try the following approach:尝试以下方法:

  1. Use a regular expression to pick out all the entries.使用正则表达式挑选出所有条目。
  2. Split the list in two and sort the pairs based on the numeric value found in each 'header' value.将列表一分为二,并根据在每个“标题”值中找到的数值对对进行排序。 Conversion to integer is needed to avoid data10 being sorted before data1 .需要转换为 integer 以避免data10data1之前排序。
  3. Build a list of the sorted key value pairs.构建已排序的键值对列表。
  4. Use a csv.writer() to create the CSV file by transposing the entries into two rows.使用csv.writer()通过将条目转换为两行来创建 CSV 文件。

For example:例如:

import re
import csv

with open('file.txt') as f_input:
    data = re.findall('\w+', f_input.read())
    items = len(data) // 2

with open('file.csv', 'w', newline='') as f_output:    
    kv = [(k, v) for k, v in sorted(zip(data[:items], data[items:]), key=lambda x: int(re.search('\d+', x[0]).group(0)))]
    csv.writer(f_output).writerows(zip(*kv))

Giving you file.csv containing:给你file.csv包含:

data1,data2,data3,data4,data5,data7,data9,data10,data11,data12,data13,data14,data15,data16
1,2,3,4,5,7,9,10,11,12,13,14,15,16

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM