Getting pandas error as: ValueError: operands could not be broadcast together with shapes (4,) (2,2)
Trying to export details in excel, i tried with below code:
Expected output: selected customer names: name1, name2 for the desig: CUST selected customer names: values name3, name4 for the desig :ORDER
Have tried below code:
import pandas as pd
import xlsxwriter
workbook = xlsxwriter.Workbook('file.xlsx')
worksheet1 = workbook.add_worksheet()
def CUST1():
df = pd.DataFrame([
['CUST', 'name1', 'PIZZA', 'A'],
['CUST', 'name2', 'DONUT', 'A'],
['ORDER', 'name3', 'CAKE','B'],
['ORDER', 'name4', 'COOKIES', 'C']
],
columns=("DESIG", "NAMES", "CITIES", "CLASS"))
ORD = pd.concat((df['DESIG'],df.groupby('DESIG')
['NAMES'].transform(lambda x: ", ".join(x))),
axis=1).drop_duplicates()
print(ORD)
for x, name in enumerate(ORD):
worksheet1.write(x, 0, "selected customer names"
+ df['DESIG'] + "for" +df.groupby('DESIG')
['NAMES'])
CUST1()
workbook.close()
This should be what you want according to the expected output provided. I just utilized the dataFrame ORD since it contains all the necessary information without having to do more data transformations.
import pandas as pd
import xlsxwriter
workbook = xlsxwriter.Workbook('file.xlsx')
worksheet1 = workbook.add_worksheet()
def CUST1():
df = pd.DataFrame([
['CUST', 'name1', 'PIZZA', 'A'],
['CUST', 'name2', 'DONUT', 'A'],
['ORDER', 'name3', 'CAKE','B'],
['ORDER', 'name4', 'COOKIES', 'C']
],
columns=("DESIG", "NAMES", "CITIES", "CLASS"))
ORD = pd.concat((df['DESIG'],df.groupby('DESIG')
['NAMES'].transform(lambda x: ", ".join(x))),
axis=1).drop_duplicates()
for x in range(len(ORD)):
worksheet1.write_string(x, 0, "selected customer names: "
+ ORD['NAMES'].iloc[x] + " for the desig: " + ORD['DESIG'].iloc[x])
CUST1()
workbook.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.