gpt4 book ai didi

python - 使用python或pandas合并多个文件

转载 作者:行者123 更新时间:2023-11-30 22:47:14 25 4
gpt4 key购买 nike

我有多个文件(最多 20 个或更多)要根据特定条件合并。下面是三个文件示例:

File1           
ID Type Condition Colour
113884 M Good Green
123456 M Good Blue
178101 U Good Yellow
245645 U Good Red
256178 X Fair Green
803989 X Poor Red

File2
ID Type Condition Colour
113884 M Good Green
123456 M Good Blue
172221 M Poor Red
178101 U Good Yellow
256178 X Fair Green

File 3
ID Type Condition Colour
113884 M Good Green
123456 M Good Blue
172221 M Poor Red
178101 U Good Yellow
178101 U Good Yellow
256178 X Fair Green
286762 Q Good Purple

我想提取并合并这些文件中的类似信息,如下面所需的输出所示。在所有文件中,任何带有“类型”M 和 Q 的行及其 ID 都会被提取,因此在输出文件中,如果 ID 和类型包含在文件中,则文件名将成为指示"is"或“否”的字段列。文件与否。

所需输出(.csv):

ID  Type    File 1  File2   File3
113884 M Yes Yes Yes
123456 M Yes Yes Yes
172221 M No Yes Yes
286762 Q No No Yes

这是我的不足尝试:

import os, glob

all_line =[]
for file in golob.glob('*.txt'):
infile = open('file', 'r')
for line in file:
line=line.strip.split('\t')
if line[1]=='M' or line[1]=='Q':
all_line.append(line)

我不知道如何使用 python 或 pandas 来做到这一点。有人可以帮忙吗?谢谢。

最佳答案

IIUC 你可以这样做:

import os
import glob
import pandas as pd

files = glob.glob(r'D:\temp\.data\File*.csv')

def merge_files(files, **kwargs):
dfs = []
for f in files:
dfs.append(
pd.read_csv(f, delim_whitespace=True, usecols=['ID','Type'])
.query("Type in ['M','Q']")
.drop_duplicates()
.assign(col=0)
.rename(columns={'col':os.path.splitext(os.path.basename(f))[0]})
.set_index(['ID','Type'])
)
return pd.concat(dfs, axis=1).notnull()


result = merge_files(files).reset_index()
print(result)

输出:

       ID Type  File1  File2 File3
0 113884 M True True True
1 123456 M True True True
2 172221 M False True True
3 286762 Q False False True

关于python - 使用python或pandas合并多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40598515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com