Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
colomns error
#1
[quote]import pandas as pd

# Location of the Excel file and the name of the sheet
file_path = r'C:\Users\elf\Desktop\BUY.xlsx'
sheet_name = 'BUYX'

# Reading the Excel file
df = pd.read_excel(file_path, sheet_name=sheet_name, header=None)

# There are numbers in column A and names in column B
df.columns = ['numbers', 'NAME', 'FROM']

# Creating an empty list to hold the results
result = []

# Temporary variables
current_name = None
current_sum = 0

# Calculate the sum of consecutive names
for index, row in df.iterrows():
    if row['NAME'] == current_name:
        current_sum += row['numbers']
    else:
        if current_name is not None:
            result.append([current_name, current_sum])
        current_name = row['NAME']
        current_sum = row['numbers']
# Add values ​​in the last row
result.append([current_name, current_sum])

# Create a new DataFrame to write the results to columns D and E
result_df = pd.DataFrame(result, columns=['NAME', 'Total'])

# Prepare columns D and E
df['D'] = ''
df['E'] = ''
df.loc[:len(result_df)-1, 'D'] = result_df['NAME']
df.loc[:len(result_df)-1, 'E'] = result_df['Total']

# Write the results to the same file
with pd.ExcelWriter(file_path, engine='openpyxl', mode='a', if_sheet_exists='overlay') as writer:
    df.to_excel(writer, sheet_name=sheet_name, index=False, header=False)

print("PROCESS COMPLETED")[/quote]
Hello friends,
In my code above, I have data in 3 columns on my Excel sheet. I'm writing them to result_df using df, but they are being written side by side. Although I have defined columns J and K in the code, it's not writing to these columns; it's writing right next to the data in df. What should I do to write to columns J and K?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020