2

In the following code, I created a function to return a DataFrame with a new column new_col with one-period shifted values of ori_col. But, a new column of the output has the name new_col rather than B. What am I missing here?

import pandas as pd

def add_col_diff(dframe, ori_col, new_col):
    shift_1 = dframe[ori_col].shift(1)
    return dframe.assign(new_col=shift_1)

data = {'A': [10, 11, 12]}
df = pd.DataFrame.from_dict(data)
df = add_col_diff(df, 'A', 'B')
df

This gives

     A  new_col
0   10  NaN
1   11  10.0
2   12  11.0
2
  • I'm actually completely confused by this. return dframe.assign('B'=shift_1) is not valid, so it presumably takes the argument name rather than its value? Commented Dec 29, 2018 at 1:20
  • Yes, return dframe.assign(B=shift_1) will work, but I don't see how you reasonably convey that Commented Dec 29, 2018 at 1:22

1 Answer 1

5

assign will set the keyword arguments as the column names. Simply having assign(new_col=shift_l) will make a column with the name new_col. Keyword arguments are not evaluated as variables.

If you want to use variables to define your column names, you can unpack from a dictionary. Try:

dframe.assign(**{new_col: shift_1})

An alternative is to use:

dframe[new_col] = shift_1
Sign up to request clarification or add additional context in comments.

5 Comments

Do you know why it works like this? The OP's attempt seems pretty reasonable to me
Keyword arguments do not resolve variables. The answer is using the correct syntax of casting a dictionary to keywords ( IE: the dictionary will resolve the variables )
@John so this is a necessary evil of allowing multiple assignments in one call?
@roganjosh not necessarily, it's just the idiom for how keyword arguments are declared. As demonstrated above, you can assign a dictionary "key" + "Value" using a variable/single call.
If this weren't the case, function keywords would need quotes around them... too much energy for those extra key presses.

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.