python - Python CSV 数据拆分
问题描述
我在 CSV 文件中有一些数据,如下所示:
- 文件所有者
- 文件 1 鲍勃、汤姆、詹姆斯
- File2 汤姆、杰克、大卫
我希望它看起来像这样:
- 文件所有者
- 文件 1 鲍勃
- File1 汤姆
- 文件 1 詹姆斯
- File2 汤姆
- File2 杰克
- File2 大卫
欢迎任何想法,我已经导入了 csv 文件。
解决方案
我希望您的 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 文件的样子:修改数据框后
推荐阅读
- flutter - 是否需要在 Hive 中注册对象列表?
- pandas - 如何将熊猫系列转换为附图所示的数据框?
- amazon-web-services - AWS - 实例上的 SSM 代理:[<>] 不起作用
- java - 将 Instant 转换为 OffsetDateTime 然后在 OffsetDateTime 上的 Instant.parse() 在零秒情况下导致 DateTimeParseException
- jekyll - 让 livereload 在 Jekyll 4.2.0 和 Bundler 上工作
- php - 不从源代码构建 PHP 时,如何在 ubuntu 容器中重新创建 docker-php-ext-configure 功能?
- flutter - 为什么 Pages 可以匹配 Navigator.push on flutter?
- python - 我不明白为什么我的循环中出现“从空列表中弹出”错误
- java - 为服务器集成测试更新外部依赖固定装置
- r - 如何有效地计算 R 中的最短路径?