简体   繁体   中英

How to merge csv file line by line python

Hello I am new to Python and I am trying to merge these two files fileA and fileB into one using this piece of code

    a = pandas.read_csv(fileA)
    b = pandas.read_csv(fileB)
    b = b.dropna(axis=1)
    merged = b.merge(a, on="day")
    merged.to_csv(output, index=False)

But the problem is instead of it merging line by line it merges the first line of fileA with all lines of fileB! below you'll find an example

content of fileA

numb,day

one,sat
two,sun  
three,mon

content of fileB

day,month,color,shape

sat,apr,black,circle
sun,may,white,triangle
mon,jun,red,square

expected output

numb,day,month,color,shape

one,sat,apr,black,circle
two,sun,may,white,triangle
three,mon,jun,red,square

what I am actually getting

numb,day,month,color,shape

one,sat,apr,black,circle
one,sat,may,white,triangle
one,sat,mon,jun,red,square
two,sun,apr,black,circle
two,sun,may,white,triangle
two,sun,jun,red,square
.
.
.

So how can I merge the files line by line instead of all of this, or what exactly am I doing wrong here?

I am using Python 3.7

Use pandas.concat to combine DataFrames:

a = pandas.read_csv(fileA)
b = pandas.read_csv(fileB)
b = b.dropna(axis=1)

merged = pd.concat([a, b], axis=1)

merged.to_csv('output.csv', index=False)

You can use pandas.join

a = pandas.read_csv(fileA)
b = pandas.read_csv(fileB)
fileA.join(fileB.set_index('day'), on='day')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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