I want Python to combine only certain columns in the csv file

Asked 1 years ago, Updated 1 years ago, 300 views

I am a beginner and may not be able to ask questions, but I appreciate your cooperation.

I want to combine only certain columns in Python.Like the first screenshot, the cells of last name and first name are separated, but I would like you to tell me how to combine them like the first screenshot and automatically combine the cells below them.

Either half-width or full-width is fine between the first and last names after the combination.

変更前

変更後

import pandas as pd
df = pd.read_csv('./offerlist.csv', encoding='cp932')
df2 = df[["Email Address", "Last Name", "First Name", "Address"]]
print(df2)
df2.to_csv('./output.csv',header=True,index=False)

Thank you in advance!

python csv

2023-03-27 03:46

2 Answers

I think you can simply add the rows as shown below.

import pandas as pd

df = pd.DataFrame({'メール':['[email protected]','[email protected]'],'姓':['tanaka','sato'],'名':['taro','hanako'],'値':[1,2]})
df['First Name'] = df['First Name'] + ' + df['First Name']
df = df[['Mail', 'First Name', 'Value']]
print(df)
#             Mail Last Name Value
#0  [email protected]  tanaka taro  1
#1  [email protected]  sato hanako  2


2023-03-27 04:40

To combine cells in Excel, use merge_cells.
Cell-bonded cells are configured with the contents of the leftmost cell, so you must save the contents of the cell before joining and set the contents of the cell-bonded cells.

import openpyxl

wb = openpyxl.load_workbook('Before Cell Join .xlsx')
ws = wb['Sheet1']
for row in ws.iter_rows():
    v1 = row[1].value #B column values before joining
    v2 = row[2].value #C column values before joining
    row_no = str(row[0].row) #line number
    cells = 'B' + row_no + ':' + 'C' + row_no
    ws.merge_cells(cells) #cellbond
    row[1].value = v1 + ' + v2 #rewrite the combined value to the cell bound
wb.save('After Cell Join .xlsx')


2023-03-27 05:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.