【问题标题】:How to split a 2-column ASCII file data to a multicolumn data properly in Python?如何在 Python 中将 2 列 ASCII 文件数据正确拆分为多列数据?
【发布时间】:2023-02-23 05:01:33
【问题描述】:

我有一个结构如下的文本文件:

0   1.23
1   2.76
2   2.46
3   6.23

0   1.33
1   2.57
2   2.87
3   5.34

.
.
.

我想安排一个新文件,例如:

0   1.23   1.33  ...
1   2.76   2.57  ...
2   2.46   2.87  ...
3   6.23   5.34  ...

我可以用一种非常原始的方式来做到这一点:

# Number of data group
numberofdatagroup = 5
# Number of data in each group
data = 4


arr = [[0 for col in range(2*numberofdatagroup)] for row in range(data)]
f = open(file, 'r')
lines = f.readlines()
f.close()
a=0
for i in range(0, numberofdatagroup, 1):
   b = 0
   for a in range (0, data, 1):
      fields = lines[a].split()
      arr[b][2*i] = fields[0]
      arr[b][2*i+1] = fields[1]
      b = b + 1
   a = a + 2

# writing to output file
f = open(output, 'w+')
stringline = ""

for i in range(0, data, 1):
  stringline = stringline + arr[i][0] + " " + arr[i][1] + " "
  for j in range(1, numberofdatagroup, 1):
     stringline = stringline + arr[i][2*j+1] + " "
  f.write(stringline + "\n")
  stringline = ""

f.close()

但是,它并不总是有效。对空行非常敏感。有没有办法用更聪明的方式来制作它?

【问题讨论】:

    标签: python file text split


    【解决方案1】:

    这是一个如何将文件读入 Pandas DataFrame 的示例:

    import pandas as pd
    
    current, all_groups = [], []
    with open('data.txt', 'r') as f_in:
        for line in map(str.strip, f_in):
            if line == "" and current:
                all_groups.append(pd.DataFrame(current)[1])
                current = []
            else:
                current.append(line.split(maxsplit=1))
    
    if current:
        all_groups.append(pd.DataFrame(current)[1])
    
    final_df = pd.concat(all_groups, axis=1)
    final_df.columns = range(len(final_df.columns))
    
    print(final_df)
    

    印刷:

          0     1
    0  1.23  1.33
    1  2.76  2.57
    2  2.46  2.87
    3  6.23  5.34
    

    编辑:没有pandas库:

    current, all_groups = [], []
    with open("data.txt", "r") as f_in:
        for line in map(str.strip, f_in):
            if line == "" and current:
                all_groups.append(current)
                current = []
            else:
                current.append(line.split(maxsplit=1))
    
    if current:
        all_groups.append(current)
    
    for g in zip(*all_groups):
        print('{} {} {}'.format(g[0][0], g[0][1], ' '.join(v for _, v in g[1:])))
    

    【讨论】:

    • 谢谢。但我只是在寻找一个基本的 Python 解决方案,而不需要加载像 pandas 这样的大型库。但是,如果找不到,也可以使用它。
    • @SeferBoraLisesivdin 我更新了没有pandas 的答案。
    猜你喜欢
    • 2021-04-26
    • 2021-10-21
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多