为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用python从另一个文件中的多个文件中提取数据?

如何使用python从另一个文件中的多个文件中提取数据?

12345678_0001 2023-06-06 16:30:59
我有一个名为“sample.csv”的 CSV 文件,它有一些列:id  name      contactno. fileName1   robin      1234455    info_v1.csv2   elsa,roy   42342442   info_v1.csv3   john       232323     info_v2.csvfileName 列中提到的文件包含一些文本消息。info_v1.csvid  message1   my name is robin. I am from Berlin2   my name is Elsa. My age is 12info_v2.csvid  message3   my name is John.I play football.现在我想创建一个包含所有信息的文件。例如:输出.csvid  name       contactno. message1   robin      1234455    my name is robin. I am from Berlin2   elsa,roy   42342442   my name is Elsa. My age is 123   john       232323     my name is John.I play football.到目前为止我所做的如下:csvfile = csv.reader(open('sample.csv', newline='',encoding="utf8"))next(csvfile)included_cols = [0, 1, 2, 3]for row in csvfile:    content = list(row[i] for i in included_cols)    filename=content[3]            with open(filename, newline='') as f:                reader = csv.reader(f)        next(reader)        for row1 in reader:                        content1 = row1            my_list1=content+content1但在这里我无法将所有信息保存在一起以创建 output.CSV,我如何匹配 id 以便它不会从 info.csv 中获取错误的数据?
查看完整描述

2 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

创建一个函数,读取文件中提到的sample.csv,然后比较id并返回相应的message


import csv


def get_message(name, id):

    with open(name) as fp:

        reader = csv.DictReader(fp)

        for row in reader:

            if row['id'] == id:

                return row['message']


with open('sample.csv') as fp, open('output.csv', 'w') as fw:

    reader = csv.reader(fp)

    writer = csv.writer(fw)

    columns = next(reader)[:-1] + ['message']

    writer.writerow(columns)

    for row in reader:

        new_row = row[:-1] + [get_message(row[-1], row[0])]

        writer.writerow(new_row)

输出:


 id      name  contactno.                             message

  1     robin     1234455  my name is robin. I am from Berlin

  2  elsa,roy    42342442       my name is Elsa. My age is 12

  3      john      232323    my name is John.I play football.


查看完整回答
反对 回复 2023-06-06
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

这是一种不同的方法,它使用pandas:


import numpy as np

import pandas as pd


df = pd.read_csv('sample.csv')

files = df['fileName'].unique()


for f in files:

    df = df.merge(pd.read_csv(f), on='id', how='left')


df['message'] = np.where(df['message_x'].isnull(), df['message_y'], df['message_x'])

df.drop(columns=['message_x', 'message_y', 'fileName'], inplace=True)

df.to_csv('output.csv', index=False)

输出:

id  name        contactno.  message

1   robin       1234455     my name is robin. I am from Berlin

2   elsa,roy    42342442    my name is Elsa. My age is 12

3   john        232323


查看完整回答
反对 回复 2023-06-06
  • 2 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信