1

I'm trying to write a function that take a pandas Dataframe as argument and at some concatenate this datagframe with another.

for exemple:

def concat(df):
    df = pd.concat((df, pd.DataFrame({'E': [1, 1, 1]})), axis=1)

I would like this function to modify in place the input df but I can't find how to achieve this. When I do

...
print(df)
concat(df)
print(df)

The dataframe df is identical before and after the function call

Note: I don't want to do df['E'] = [1, 1, 1] because I don't know how many column will be added to df. So I want to use pd.concat(), if possible...

1 Answer 1

1

This will edit the original DataFrame inplace and give the desired output as long as the new data contains the same number of rows as the original, and there are no conflicting column names.

It's the same idea as your df['E'] = [1, 1, 1] suggestion, except it will work for an arbitrary number of columns.

I don't think there is a way to achieve this using pd.concat, as it doesn't have an inplace parameter as some Pandas functions do.

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'C': [10, 20, 30], 'D': [40, 50, 60]})
df[df2.columns] = df2

Results (df):

   A  B   C   D
0  1  4  10  40
1  2  5  20  50
2  3  6  30  60
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.