简体   繁体   English

Python pandas - 将 groupby output 写入文件

[英]Python pandas - writing groupby output to file

I used the following to get proportion information on my data:我使用以下方法获取有关我的数据的比例信息:

>>>testfile = pd.read_csv('CCCC_output_all_FINAL.txt', delimiter="\t", header=0)
>>> testdf = pd.DataFrame({'Proportion': testfile.groupby(('Name','Chr','Position','State')).size() / 39})
>>> testdf.head(5)
                                        Proportion
Name    Chr Position  State           
S-3AAAA 16  27557749  4        0.025641
                                    5        0.076923
                                    6        0.025641
S-3AAAC 15  35061490  2        0.076923
                                    4        0.025641

>>> testdf.to_csv('CCCC_output_summary.txt', sep='\t', header=True, index=False)

The output file only has the column Proportion . output 文件只有Proportion列。 I'd like the following table output:我想要下表 output:

Name    Chr    Position     State     Proportion
S-3AAAA  16     27557749     4         0.025641
S-3AAAA  16     27557749     5         0.076923
S-3AAAA  16     27557749     6         0.025641
S-3AAAC  15     35061490     2         0.076923
S-3AAAC  15     35061490     4         0.025641

Is it possible/easy to write the pandas output to a file like this?是否可以/容易地将 pandas output 写入这样的文件?

使用reset_index()

testdf.reset_index().to_csv('CCCC_output_summary.txt', sep='\t', header=True, index=False)

Recently, I had to work with an Excel file that has 2 columns, with headers 'Dog Breed' and 'Dog Name'.最近,我不得不处理一个 Excel 文件,该文件有 2 列,标题为“Dog Breed”和“Dog Name”。 I came up with the following code (tested with Python 3.11.0 ) that uses groupby() and prints the grouped data into a .csv file.我想出了以下代码(使用Python 3.11.0测试),它使用groupby()并将分组数据打印到.csv文件中。

from pathlib import Path
import pandas as pd

p = Path(__file__).with_name('data.xlsx')
q = Path(__file__).with_name('data-grouped.csv')

df = pd.read_excel(p)
groups = df.groupby('Dog Breed', sort=False)

with q.open('w') as foutput:
for g in groups: # For each group
    foutput.write(f"{g[0]}, {len(g[1])}") # Record the number of dogs in each group
    for e, (index, row) in enumerate(g[1].iterrows()): # Iterating over the group's dataframe
        name = str(row['Dog Name'])
        if(e == 0):
            mystr = f",{name}\n"
        else:
            mystr = f",,{name}\n"
        foutput.write(mystr)

data.xlsx:

在此处输入图像描述

data-grouped.csv:

在此处输入图像描述

I had the same problem. 我有同样的问题。 reset_index() as explained above did not work for me. 如上所述的reset_index()对我不起作用。 I used an answer from another Stackoverflow and it worked wonderfully. 我使用了另一个Stackoverflow的答案,效果很好。 Details are below. 详细信息如下。

Input csv has data under following two columns: Item Code, Quantity 输入的csv在以下两列中包含数据:项目代码,数量

Output needed: Average quantity grouped by item and both columns to be part of csv. 需要的输出:按项目和两列分组的平均数量,将其作为csv的一部分。

Initial code: 初始代码:

import pandas as pd

data_directory = os.path.join("D:\\data")
df = pd.read_csv(os.path.join(data_directory, "input_file.csv"))

df_avg = df.groupby("Item Code")["Quantity"].mean()
df_avg.reset_index().to_csv(os.path.join(data_directory,'output_file.csv'), sep='\t', header=True, index=False )

Output received: Only the average quantity was written to output file 收到输出:仅将平均数量写入输出文件

Following code solved the problem: 以下代码解决了该问题:

import pandas as pd

data_directory = os.path.join("D:\\data")
df = pd.read_csv(os.path.join(data_directory, "input_file.csv"))

df.groupby("Item Code")["Quantity"].mean().reset_index()[["Item Code", "Quantity"]].to_csv(os.path.join(data_directory,'output_file.csv'))

By the above code, I got the output file which has two columns: Item Code and Quantity and the second column contains average of quantity for each Item code. 通过上面的代码,我得到了包含两列的输出文件:项目代码和数量,第二列包含每个项目代码的数量平均值。

Other stack overflow reference: Pandas groupby to to_csv 其他堆栈溢出参考: Pandas groupby到to_csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM