DataFrame 赋值内部函数
DataFrame assign inside function
我对 df assign 函数有疑问。使用此功能时,我必须输入不带撇号的列名。为什么会这样,我可以规避它吗?请参阅下面的示例
df = pd.DataFrame(columns=['Grade'])
df['Grade'] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
df_temp = df.assign(Grade='Total')
def dummy(df, _g):
# if I write grade here then I get the expected result
return df.assign(_g='Total')
# here I want grade to be assigned to total but it creats a new variable called _g
df_temp = dummy(df, 'Grade')
def dummy(df, _g):
return df.assign(**{_g: 'Total'})
我对 df assign 函数有疑问。使用此功能时,我必须输入不带撇号的列名。为什么会这样,我可以规避它吗?请参阅下面的示例
df = pd.DataFrame(columns=['Grade'])
df['Grade'] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
df_temp = df.assign(Grade='Total')
def dummy(df, _g):
# if I write grade here then I get the expected result
return df.assign(_g='Total')
# here I want grade to be assigned to total but it creats a new variable called _g
df_temp = dummy(df, 'Grade')
def dummy(df, _g):
return df.assign(**{_g: 'Total'})