首页 > 解决方案 > Python CSV 数据拆分

问题描述

我在 CSV 文件中有一些数据,如下所示:

  1. 文件所有者
  2. 文件 1 鲍勃、汤姆、詹姆斯
  3. File2 汤姆、杰克、大卫

我希望它看起来像这样:

  1. 文件所有者
  2. 文件 1 鲍勃
  3. File1 汤姆
  4. 文件 1 詹姆斯
  5. File2 汤姆
  6. File2 杰克
  7. File2 大卫

欢迎任何想法,我已经导入了 csv 文件。

标签: pythoncsv

解决方案


我希望您的 csv 文件以前看起来像这样: 在修改 csv 文件之前

# I used pandas for this
import pandas as pd
#converting csv file to dataframe
df =pd.DataFrame(pd.read_csv("dataframe.csv"))

#converts the Files column into a list
files = df['File'].to_list()

#This will be the new dataframe which is a modified version of the first one
new_df = pd.DataFrame(columns=['File', 'Owner'])

for file,row in zip(files,range(len(df.index))):
    # separates the owners from the Owners column, separator is (', ')
    Owners = df.iloc[row,1].split(", ")
    for owner in Owners:
        #Adds the new rows to the dataframe by filename and owner
        new_row ={'File':file,'Owner':owner}
        new_df = new_df.append(new_row,ignore_index=True)

#convert the new dataframe into a csv file
new_df.to_csv('modified_dataframe.csv',index=False)

这是新的 csv 文件的样子:修改数据框后


推荐阅读