1

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.

email, email, phone, phone, phone, name, address
[email protected], [email protected], 90192, 2980, 9203, John Doe, 82 High Street
[email protected], [email protected], 1341, 55, 665, Roe Jan, 11 Low Street
[email protected],,, 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?

3
  • You can not have duplicate column names in pandas Commented Feb 19, 2019 at 9:10
  • Assuming you want the output in csv for viewing it in excel or similiar, you could add blank spaces after the key phone. E.g. "phone", "phone ", "phone ". But why not label the columns based on the different use case of each phone-number? Commented Feb 19, 2019 at 9:17
  • @f.wue I cannot label them differently, I have no choice but to follow their format that contains duplicate names Commented Feb 19, 2019 at 9:33

3 Answers 3

1

You could get it done using csv:

list.txt:

email, email, phone, phone, phone, name, address
[email protected], [email protected], 90192, 2980, 9203, John Doe, 82 High Street
[email protected], [email protected], 1341, 55, 665, Roe Jan, 11 Low Street
[email protected],,, 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):

out

Sign up to request clarification or add additional context in comments.

Comments

1

Build your dataframe with different column names (email01, email02...) and then use a header list on output:

df.to_csv("file.csv",header=['email', 'email', 'phone', 'phone', 'phone', 'name', 'address'])

Comments

0

Use pd.conact to add columns with the same name:

df = pd.concat([df1, df2], axis=1)

It will concatenate all columns, even if some of them have the same name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.