【发布时间】: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