Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Need to combine two column of two dataframe or two column of same dataframe

I have two dataframes. I want to combine two different columns of same/different dataframe. I have column names are different in both data frame.

I have tried as per below. But the output is not as per expectation.

import pandas as pd

df1 = pd.DataFrame({
    'A': ['a','a','a'],
    'B': range(3)
})

df2 = pd.DataFrame({
    'C': ['c','c','c'],
    'D': ['4','5','6']
})

df = df1.join(df2)

print (df)

But I am expecting output under columns A and B of df1 as per below.

enter image description here

Please have a look and help me with the same.

question from:https://stackoverflow.com/questions/66061912/need-to-combine-two-column-of-two-dataframe-or-two-column-of-same-dataframe

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

1 Answer

0 votes
by (71.8m points)

I think you need rename like mentioned @wwnde in comments:

df = df1.append(df2.rename(columns={'C':'A','D':'B'}), ignore_index=True)

Or:

df = pd.concat([df1, df2.rename(columns={'C':'A','D':'B'})], ignore_index=True)

If need set columns dynamic by dictionary created from columns names with zip:

d = dict(zip(df2.columns, df1.columns))
df = df1.append(df2.rename(columns=d), ignore_index=True)
print (df)
   A  B
0  a  0
1  a  1
2  a  2
3  c  4
4  c  5
5  c  6

EDIT:

df1 = pd.DataFrame({ 'A': ['a1','a2','a3'], 'B': range(3), 'C': ['c1','c2','c3'], 'D': ['4','5','6'] })

df = df1[['A','B']].append(df1[['C','D']].rename(columns={'C':'A','D':'B'}), ignore_index=True)
print (df)
    A  B
0  a1  0
1  a2  1
2  a3  2
3  c1  4
4  c2  5
5  c3  6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...