簡體   English   中英

如何根據其中一列中的條件以多個塊導出 pandas dataframe.to_csv(類似於 groupby)

[英]How to export pandas dataframe .to_csv, in multiple chunks, based upon criteria in one of the columns (similar to groupby)

我有一個 dataframe 已經由Dr排序:

>>> df
         Date  Dr  Cr  Amount  Cum Sum
0 2022-01-01  B1  D1    1000     1000
3 2022-01-05  B1  E1    -500      500
2 2022-01-01  D1  B1   -1000    -1000
1 2022-01-05  E1  B1     500      500

df.to_csv(index=False)產生: 在此處輸入圖像描述

但是,我想導出.to_csv()以便每個新條目都從下一個Dr值開始。

我嘗試了不正確的解決方案,例如df.groupby('Dr').to_csv(index=False)以及其他帶有.to_csv(mode='a')解決方案,但沒有任何運氣。

理想情況下,將實現以下.csv output,空格, Dr的名稱和 dataframe 標題重復:

在此處輸入圖像描述

謝謝你。

您是否考慮過遍歷列中的唯一值並過濾 dataframe?

你可以嘗試類似的東西

for dr_value in df.Dr.unique():
    df[df.Dr==dr_value].to_csv(f"filename_{dr_value}.csv", index=False)

在我看來,它是一個非常定制的解決方案,我認為您不能為此使用 pandas。

數據

import pandas as pd

data = {'Date': {0: '2022-01-01', 1: '2022-01-05', 2: '2022-01-01', 3: '2022-01-05'},
 'Dr': {0: 'B1', 1: 'B1', 2: 'D1', 3: 'E1'},
 'Cr': {0: 'D1', 1: 'E1', 2: 'B1', 3: 'B1'},
 'Amount': {0: '1000', 1: '-500', 2: '-1000', 3: '500'},
 'CumSum': {0: '1000', 1: '500', 2: '-1000', 3: '500'}}

df = pd.DataFrame(data)

分組並寫入文件

lst = list(df.groupby("Dr"))

cols = df.columns
with open('file.txt', 'w') as f:
    for l in lst:
        f.write(l[0])
        f.write('\n')
        for col in cols[:-1]:
            f.write(f"{col} ")
        f.write(f"{cols[-1]}\n")
        for i, row in l[1].iterrows():
            for col in cols[:-1]:
                f.write(f"{row[col]} ")
            f.write(f"{row[cols[-1]]}\n")
        f.write("\n")

您需要將applygroupby一起使用

import pandas as pd

filename = 'your-filename.csv'
groupby_col = 'Dr'

def write_csv(df):
    group = df[groupby_col].iat[0]

    # first write only group name to the file using a temporary dataframe
    header_df = pd.DataFrame(group, index=[0], columns=['group'])
    header_df.to_csv(filename, index=False, mode='a', header=False)

    # now write the data
    df.to_csv(filename, index=False, mode='a')


df = pd.read_csv(r'.\POC\files\drcr.csv')
df.groupby(groupby_col).apply(write_csv)
print("Done")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM