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
171 views
in Technique[技术] by (71.8m points)

python - Appending columns of DataFrame to other DataFrame

I have two DataFrames with only one row and distinct columns:

df1 = pd.DataFrame(columns=list('ABC'))
df1.loc[0] = [1,2,3]

df2 = pd.DataFrame(columns=list('DE'))
df2.loc[0] = [18,3]

Now I would like to append the column of df2 to the right of df1. I have tried the following:

temp = pd.concat([df1.reset_index(), df2.reset_index()], axis=1)

The problem here is that also two index columns are added which I don't want. If I add ignore_index = True then the index columns are not added but all column names are removed. That is also not what I want.

Is there a workaround?

question from:https://stackoverflow.com/questions/65832343/appending-columns-of-dataframe-to-other-dataframe

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

1 Answer

0 votes
by (71.8m points)

You can probably set the index of df2 to be the same as df1

df1 = pd.DataFrame(columns=list('ABC'))
df1.loc[0] = [1,2,3]

df2 = pd.DataFrame(columns=list('DE'))
df2.loc[0] = [18,3]

This will keep the index of df1

df2.index = df1.index

temp = pd.concat([df1, df2], axis=1)

if you don't care about the index at all you can reset and drop the index


temp = pd.concat([df1.reset_index(drop=True), df2.reset_index(drop=True)], axis=1)

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

...