Pandas: df.assign in for loop

Created on 6 Nov 2019  路  2Comments  路  Source: pandas-dev/pandas

Code Sample, a copy-pastable example if possible

list_of_columns = ["name", "weight"]

for column in list_of_columns:
    if column in other_df.columns:
        df = df.assign(column = other_df[column])

Problem description

df.assign creates a new column called "column" and then overwrites it with another new column called "column" instead of adding the collumns "name" and "weight". i think its because of the use of an equal sign instead of colon or comma.

i would like to have an "assign" function, that i can use in a for loop.

im sorry if im wrong or if this is not the right place for this issue. im quite new to programming.

regards
Florian

Usage Question

Most helpful comment

Assign uses keyword arguments. Keywords arguments are basically just dictionaries being passed. Using dictionaries and using argument unpacking, you can use the value of the string instead. Like this:

df.assign(**{column: other_df[column]})

You can even go more advanced in with this by instead of using for loops, using a dictionary comprehension.

df.assign(**{column: other_df[column] for column in list_of_columns if column in other_df.columns})

All 2 comments

The Github Issues board is for bugs and enhancement requests for the library. For usage questions, we recommend using Stack Overflow.

Assign uses keyword arguments. Keywords arguments are basically just dictionaries being passed. Using dictionaries and using argument unpacking, you can use the value of the string instead. Like this:

df.assign(**{column: other_df[column]})

You can even go more advanced in with this by instead of using for loops, using a dictionary comprehension.

df.assign(**{column: other_df[column] for column in list_of_columns if column in other_df.columns})
Was this page helpful?
0 / 5 - 0 ratings