【问题标题】:Writing pandas dataframes to multiple excel files将 pandas 数据帧写入多个 excel 文件
【发布时间】:2021-09-06 05:20:04
【问题描述】:

Image shows a pandas dataframe

import pandas as pd
import numpy as np

file = '/Dummy.xlsx'

Customer = pd.read_excel(file, sheet_name=0)
Items = pd.read_excel(file, sheet_name=1)
Commission = pd.read_excel(file, sheet_name=2)
Price = pd.read_excel(file, sheet_name=3)
Sheet1 = pd.read_excel(file, sheet_name=4) 

Inner_join = pd.merge(Price,Sheet1,on = 'Item_ID', how='inner')

Inner_join = pd.merge(Price, Sheet1,on = 'Item_ID', how='inner').merge(Commission, on = 'Commission_ID')

joined_table = pd.merge(Inner_join, Customer, right_on = 'Customer_ID', left_on = 'Customer_ID_x', how = 'inner')

final_table = joined_table[['Date','Customer_Name', 'Customer_ID','Item_Name', 'Commission', 'Qty','Base_Price','Rate']]

calculated_commission = final_table[final_table.loc[:,'Base_Price'] < final_table.loc[:, 'Rate']]

calculated_commission['final_com'] = cal_com.loc[:, 'Qty'] * cal_com.loc[:, 'Commission']][2]

customers = calculated_commission['Customer_Name'].unique()

for i in customers:
    a = calculated_commission[calculated_commission['Customer_Name'].str.match(i)]
    a.to_excel(i+'.xlsx')

我正在尝试遍历唯一的客户名称并将它们写入不同的 excel 文件并使用相同的名称命名。

它创建了两个文件,但只在第二个文件“Chef Themiya”上写入数据

访问以下数据集链接:

https://drive.google.com/file/d/1VWc_WoN1nTWiDKK1YDtIXtzaAGdgbfpl/view?usp=sharing

请帮忙

【问题讨论】:

  • 将您的原始数据集添加为文件或文本,而不仅仅是图像。添加用于从数据集中生成数据框的代码。将您的预期输出添加为文件或文本,而不仅仅是描述。
  • 我已经添加了我使用的整个代码和数据集@Joshua的链接

标签: python pandas dataframe


【解决方案1】:

str.match 没有选择客户名称的模式,因为您的字符串中有括号。改用这个。

df = pd.DataFrame({'Customer': ['88 Chinese Restaurant (Pvt) Ltd', 'Chef Themiya'], 'data': [1,2]})
customers = df['Customer'].unique()
for i in customers:
    test = df[df['Customer']== i]
    print(test)

你也可以使用

df = pd.DataFrame({'Customer': ['88 Chinese Restaurant (Pvt) Ltd', 'Chef Themiya'], 'data': [1,2]})
customers = df['Customer'].unique()
for i in customers:
    test = df[df['Customer'].str.contains(i, regex=False)]
    print(test)
       Customer  data
0  88 Chinese Restaurant (Pvt) Ltd     1

       Customer  data
1  Chef Themiya     2

将您的数据集发布为图像会使您的示例难以重现。研究创建最少的可重现示例。

https://stackoverflow.com/help/minimal-reproducible-example

【讨论】:

  • 我已经添加了我使用的整个代码和数据集的链接。如果我的客户名单很长,如何用您的解决方案解决这个问题。
  • 这两种方法都适用于任意数量的客户。
  • 如果我要将它们写在同一个excel的不同工作表中并用客户名称重命名工作表,我该怎么办?我什至试图总结 fina_com 专栏并在该专栏的末尾提及。如果你知道怎么做,请帮忙。
  • 我认为这个帖子应该可以帮助您stackoverflow.com/questions/42370977/… 而不是将工作表命名为 x1、x2... 用客户名称替换它们
猜你喜欢
  • 2017-07-22
  • 2023-03-22
  • 1970-01-01
  • 2021-06-06
  • 2019-05-10
  • 2021-05-15
  • 2018-02-26
  • 2016-03-23
  • 1970-01-01
相关资源
最近更新 更多