简体   繁体   English

使用Pandas Python将系列插入CSV文件的特定列

[英]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.

相关问题 如何在 pandas 的 csv 文件的特定列的行范围内插入文本? - How to insert text in a range of row in a specific column in a csv file in pandas? 如何在csv文件python中的特定列下插入数据 - How to insert data underneath a specific column in csv file python 如何将Pandas Series插入现有Excel文件的特定列中(而不从该文件中删除内容)? - How to insert a Pandas Series into a specific column of an existing Excel file (without deleting content from that file)? 使用Python熊猫将列添加到特定的CSV行 - Add column to a specific CSV row using Python pandas 如何在使用 pandas 读取文件时删除 csv 文件的特定列? - How to drop a specific column of csv file while reading it using pandas? 使用Python csv模块覆盖csv文件中的特定列 - Overwrite a specific column in a csv file using Python csv module 在Python中使用Pandas从CSV文件读取特定数据 - Using Pandas to read specific data from a CSV file in Python 使用 Python Pandas 从列(csv 文件)中的值中删除逗号 - Removing comma from values in column (csv file) using Python Pandas 使用 Python 拆分 CSV (Pandas DataFrame) 文件的列 - Splitting Column of a CSV (Pandas DataFrame) file using Python 如何使用熊猫或普通python覆盖csv文件的特定列? - How to overwrite a particular column of a csv file using pandas or normal python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM