【问题标题】:Python. Select columns from file1 that have matching names in rows of file2Python。从 file1 中选择在 file2 的行中具有匹配名称的列
【发布时间】:2021-09-23 05:05:44
【问题描述】:

我有一个巨大的文件 file1.txt,看起来像这样:

POS 1 1 7 7 11 11 12  
1625 1 2 0 1 1 0 2
2864 2 2 1 2 1 2 1

第一行有列名(整数;请注意,有些列的名称相同,但行中的值不同),并且列之间用一个空格分隔。

我有另一个文件 file2.txt,其中包含来自 file1.txt 的列名子集,每行一个:

1
11
12

使用 python,我想得到一个 file3.txt,其中包含 file1.txt 中与 file2.txt 匹配的列名的所有列:

POS 1 1 11 11 12  
1625 1 2 1 0 2
2864 2 2 1 2 1

我尝试了以下方法:

import numpy as np
import pandas as pd

with open("file2.txt") as file_in:
lines = []
for line in file_in:
    lines.append(line)
    
df = pd.read_csv('file1.txt', sep=' ')

for x in df.columns: 
# add line of code
        lines.append(x) 
print (lines)

我在这里找到了类似的 bash 解决方案:Extract columns from a file based on header selected from another file

但是,此解决方案似乎不适用于具有重复名称的列。

【问题讨论】:

  • 问题陈述是什么?

标签: python


【解决方案1】:

希望下面的代码对你有帮助

import pandas as pd

with open("b.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line.strip())
print(lines)
# Lines is like ['1', '11', '12']
df = pd.read_csv('a.txt', sep=' ', dtype=str, header=None)
print(df)
"""
df is like 
      0  1  2  3  4   5   6   7
0   POS  1  1  7  7  11  11  12
1  1625  1  2  0  1   1   0   2
2  2864  2  2  1  2   1   2   1


"""
requirement = []
idx = 0
for x in list(df.iloc[0, :]):
    if x in lines:
        k = list(df.iloc[:, idx])
        requirement.append(k)
    idx += 1
print(requirement)
"""requirement is like 
[['1', '1', '2'], ['1', '2', '2'], ['11', '1', '1'], ['11', '0', '2'], ['12', '2', '1']]
"""
print(pd.DataFrame(requirement).T)
"""pd.DataFrame(requirement).T is like
   0  1   2   3   4
0  1  1  11  11  12
1  1  2   1   0   2
2  2  2   1   2   1
"""
pd.DataFrame(requirement).T.to_csv("c.txt", header=False, index=False, sep=" ")

【讨论】:

  • 嗨@danish bansal。我仍然得到具有非重复列的相同输出数据框。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 2023-04-03
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多