从一个 pandas 数据框中写入多个文件 [英] Writing multiple files from one pandas dataframe

查看:65
本文介绍了从一个 pandas 数据框中写入多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件,我试图将其提取并分解为多个部分.它有10列.我当前的脚本(下面显示一行)要求用户输入两列(例如A和C列),并从第三列(F列)获取数据,并将A列和F列写入新的CSV文件.

I have a CSV file that I'm trying to extract and break down into parts. It 10 columns. My current script (a line of which is shown below) asks user for input of two columns (say columns A and C) and gets data from the third (column F) and writes columns A and F to a new CSV file.

df1 = data.columnF[(data['columnA'] == data_name) & (data['columnC'] == study_name)]

当前输出看起来像这样:

Current output looks something like this:

name1,study1
name1,study2
name1,study2
name5,study9
name6,study6
name6,study0

相反,我希望输出为多个文本文件(通过跳过将所有内容写入CSV文件然后将其分成大块的步骤).

Instead, I want the output to be multiple text files (by skipping the step of writing everything to CSV file and then breaking it into chunks).

File 'name1.txt' should have
study1
study2 (only once, without repetition) 

类似地,

name5.txt > study9
name6.txt > study6
            study0

我该怎么办?

推荐答案

使用groupby并在每个组中循环:

Use groupby and loop in each group:

df_grouped = data.columnF[(data['columnA'] == data_name) & (data['columnC'] == study_name)].drop_duplicates().groupby('columnA')
for index, group in df_grouped:
    group.to_csv(index + '.text')

这篇关于从一个 pandas 数据框中写入多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆