简体   繁体   中英

Merge different 3 files according to match on the column by python

I have 3 different files like

p1 :

     x  y       
1    a  c
2    b  c
3    d  c
4    d  c

p2 :

    x1   y1  
1    b    n
2    a    n
3    a    n

and I have different file (p3) which has bunch of x id like 1a, 2b, etc. and I would like to indicate if y column corresponding n or c according to the id on x.

I tried

df3 = pd.merge(p3,p2,on='x1',how='right') or
df3 = pd.merge(p3,p1)  but it did not work.

Could you help me?

There many ways to do this, and depends on the size of your data. I would do the following.

  1. Concatenate p1 and p2

  2. Create a dictionary that maps ID to value

  3. Apply to p3

    p2.rename(columns={"x1": "x", "y1": "y"}, inplace=True)

    p = pd.concat([p1, p2], axis=0)

    dictValues = dict(zip(p["x"].tolist(), p["y"].tolist()))

    p3["y"] = p3["x"].map(dictValues)

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