简体   繁体   English

使用 pandas 将列表列表写入现有 csv 文件

[英]Writing list of lists into an existing csv file using pandas

I want to add values from a list pair1 to a new column with the corresponding name.我想将列表pair1中的值添加到具有相应名称的新列中。

pair1 = [['ab','bc','cd'],['cd','de','ef'],['sa','hg','gh','de']]

I am using pandas to add a new column to the csv file but inserting a whole list into a single cell is throwing error.我正在使用pandas向 csv 文件添加新列,但将整个列表插入单个单元格会引发错误。 If I use zip(pr1), it is inserting the index position of the zip file.如果我使用 zip(pr1),它将插入 zip 文件的索引 position。

csv_source_1 = pd.read_csv('D:\\Python 
Automation\\Rough\\Source_1.csv',error_bad_lines=False)
pair1 = [['ab','bc','cd'],['cd','de','ef'],['sa','hg','gh','de']]
for pr1 in pair1:
        csv_source_1['pair1'] = pr1
csv_source_1.to_csv('D:\\Python Automation\\Rough\\Source_1.csv')

I am looking for below as output:

eid ename     pairs
1   james    'ab','bc','cd'
2   thomas   'cd','de','ef'

The error I receive is:我收到的错误是:

ValueError: Length of values does not match length of index

Replace the for loop with below用下面的替换 for 循环

pair1 = [['ab','bc','cd'],['cd','de','ef'],['sa','hg','gh','de']]

csv_source_1['pair1'] = pd.Series(pair1)
csv_source_1['pair1'] = csv_source_1['pair1'].map(lambda x: ",".join(x))

csv_source_1.to_csv('D:\\Python Automation\\Rough\\Source_1.csv')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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