[英]How to dynamically add columns with same name on a pandas DataFrame?
I have a list of emails, phones and user info that I want to output in csv but I need to follow a format that contains duplicate columns.我有一个电子邮件、电话和用户信息列表,我想以 csv 格式输出,但我需要遵循包含重复列的格式。
email, email, phone, phone, phone, name, address
jo@doe.com, re@ko.com, 90192, 2980, 9203, John Doe, 82 High Street
re@doe.com, az@ko.com, 1341, 55, 665, Roe Jan, 11 Low Street
red@doe.com,,, 55, 111, Roe Jan, 11 Low Street
Is this possible in pandas?这在熊猫中可能吗? What is the best way of adding rows and columns with same name?
添加具有相同名称的行和列的最佳方法是什么?
You could get it done using csv
: 您可以使用
csv
完成此操作:
list.txt: LIST.TXT:
email, email, phone, phone, phone, name, address
jo@doe.com, re@ko.com, 90192, 2980, 9203, John Doe, 82 High Street
re@doe.com, az@ko.com, 1341, 55, 665, Roe Jan, 11 Low Street
red@doe.com,,, 55, 111, Roe Jan, 11 Low Street
and then: 接着:
import csv
with open('list.txt', 'r') as readFile:
reader = csv.reader(readFile)
lines = list(reader)
with open('people.csv', 'w') as writeFile:
writer = csv.writer(writeFile)
writer.writerows(lines)
readFile.close()
writeFile.close()
OUTPUT (people.csv): 输出(people.csv):
使用不同的列名(email01,email02 ...)构建数据框,然后在输出中使用标题列表:
df.to_csv("file.csv",header=['email', 'email', 'phone', 'phone', 'phone', 'name', 'address'])
Use pd.conact to add columns with the same name:使用 pd.conact 添加同名列:
df = pd.concat([df1, df2], axis=1)
It will concatenate all columns, even if some of them have the same name.它将连接所有列,即使其中一些列具有相同的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.