简体   繁体   中英

Pandas Dataframe: I want to merge two cells with same value into one

My excel sheet looks like this:- 在此处输入图像描述

I need output in this format:

在此处输入图像描述

Here is the code which I am using to generate the excel sheel:-

import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 10, 20, 30, 20, 15, 30, 45], 'Value': [1,2,3,4,5,6,7,8]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1', index=False)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Please help me.

Thank you.

Here is a working example with empty strings in the duplicated Data column cells:

df = pd.DataFrame({'Data': [10, 10, 20, 30, 20, 15, 30, 45], 'Value': [1,2,3,4,5,6,7,8]})
duplicated_data = df.Data.duplicated(keep='last')
df.Data = df.Data.where(~duplicated_data, '')
df

Will this work for your case?

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.

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