terry5546
terry5546

Reputation: 111

Combine 2 csv file with new row in Python

I have 2 csv file

1)

CustomerID
ID001
ID002
ID003
ID004
ID005
ID006
ID007
ID008
ID009

enter image description here

2.

MiniID
1001
1002
1003
1005
1006
1007
1008
1009
1010

enter image description here

How can I combine them together in 1 single Csv file? Note: I do not want to specific which column to combine, I just want the new data to be combine with the first csv file. I had tried to combine them but the new added value is showing at the bottom instead beside it.

enter image description here

My code

import os
import glob
import pandas as pd
os.chdir("C:/Users/crayx/PycharmProjects/xxx/Csv")

extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
#combine all files in the list
combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames ])
#export to csv
combined_csv.to_csv( "combined_csv.csv", index=False, encoding='utf-8-sig')

Expected Output:

enter image description here

Upvotes: 1

Views: 134

Answers (3)

Antjes
Antjes

Reputation: 120

Create a new column in the original dataframe with the content of the column of the second dataframe. Something like this:

my_csvs = [pd.read_csv(f) for f in all_filenames]
my_csv = my_csvs[0]
for csv in my_csvs[1:]:
    for column in csv.columns:
        my_csv[column] = csv[column]

PS: code has not been tested

Upvotes: 1

Vladislava Gonchar
Vladislava Gonchar

Reputation: 109

When you use concat try to add axis=1 and ignore_index=True as it in documentation here

Upvotes: 2

Jose Mar
Jose Mar

Reputation: 694

Try adding axis=1 as the paramter. Because the pd.concat cancats the two dataframe on the axis=0 by default

combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames ], axis=1)

Upvotes: 2

Related Questions