亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用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 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號