Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

python - Concatenate distinct columns in two dataframes using pandas (and append similar columns)

My question is closely related to Pandas Merge - How to avoid duplicating columns but not identical.

I want to concatenate the columns that are different in three dataframes. The dataframes have a column id, and some columns that are identical: Ex.

df1

id place name qty unit A 
1 NY    Tom   2  10   a
2 TK    Ron   3  15   a
3 Lon   Don   5  90   a
4 Hk    Sam   4  49   a

df2

id place name qty unit B 
1 NY    Tom   2  10   b
2 TK    Ron   3  15   b
3 Lon   Don   5  90   b
4 Hk    Sam   4  49   b

df3

id place name qty unit C D
1 NY    Tom   2  10   c d
2 TK    Ron   3  15   c d
3 Lon   Don   5  90   c d
4 Hk    Sam   4  49   c d

Result:

id place name qty unit A B C D
1 NY    Tom   2  10   a b c d
2 TK    Ron   3  15   a b c d
3 Lon   Don   5  90   a b c d
4 Hk    Sam   4  49   a b c d

The columns place, name, qty, and unit will always be part of the three dataframes, the names of columns that are different could vary (A,B,C,D in my example). The three dataframes have the same number of rows.

I have tried:

cols_to_use = df1.columns - df2.columns
dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer')

The problem is that I get more rows than expected and columns renamed in the resulting dataframe (when using concat).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using reduce from functools

from functools import reduce
reduce(lambda left,right: pd.merge(left,right), [df1,df2,df3])
Out[725]: 
   id place name  qty  unit  A  B  C  D
0   1    NY  Tom    2    10  a  b  c  d
1   2    TK  Ron    3    15  a  b  c  d
2   3   Lon  Don    5    90  a  b  c  d
3   4    Hk  Sam    4    49  a  b  c  d

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...