[英]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'. 我正在读取XLS文件,并将单个列的内容提取到一系列“用户名”中。 Now I want to insert the series into a CSV file which has a column named as 'Username'.
现在,我要将系列插入到CSV文件中,该文件具有名为“用户名”的列。 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”文件的“用户名”列中。
Test.csv file has many columns and I want to identify "Username" column and insert this series into that column. Test.csv文件具有许多列,我想标识“用户名”列,并将此系列插入该列。
I am facing difficulty while doing the same as I'm new in python & pandas. 与Python和Pandas的新功能相同时,我遇到了困难。
Assuming the Whois
column contains the usernames in the xls file, first read the csv 'test.csv' into memory: 假设
Whois
列包含xls文件中的用户名,请首先将csv'test.csv'读取到内存中:
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. 现在,如果“ test.csv”中已经存在“用户名”列,那么您只需选择该列并为其分配用户名系列值即可。 This is also assuming that the index length is same across the series and the
testdf
dataframe: 这还假设整个系列和
testdf
数据帧的索引长度相同:
testdf['Usernames'] = usernames
testdf.to_csv('test.csv', encoding='utf-8', index=False, header=True)
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.