简体   繁体   中英

Insert a series into specific column of a CSV file using Pandas Python

I am reading a XLS file and fetching the contents of a single column into a series 'username'. Now I want to insert the series into a CSV file which has a column named as 'Username'. I am having trouble doing this.

#Reading XLS File
excel_file = 'Some Report.xls'
sm_file = pd.read_excel(excel_file)

#Series
usernames = sm_file['Whois']

Now, I want to insert this series into "Username" column of "test.csv" file.
Test.csv file has many columns and I want to identify "Username" column and insert this series into that column.

I am facing difficulty while doing the same as I'm new in python & pandas.

Assuming the Whois column contains the usernames in the xls file, first read the csv 'test.csv' into memory:

import pandas as pd
usernames = sm_file['Whois']
testdf = pd.read_csv('test.csv')

Now, if the 'Usernames' column already exists in 'test.csv', then you can just select the column and assign the usernames series value to it. This is also assuming that the index length is same across the series and the testdf dataframe:

testdf['Usernames'] = usernames
testdf.to_csv('test.csv', encoding='utf-8', index=False, header=True)

I hope this helps.

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