如何将新列作为字符串分配给Pandas Assign

我如何将字符串作为newcolumn分配给pandas.assign

例:

newcolumn = 'myColumn'
    if(newcolumn != ''):
      sourcePandas = sourcePandas.assign(newcolumn = sourcePandas[row['PrimaryColumn']].apply(func))

Above doesn't throw any error, but creates new column with name newcolumn instead myColumn

评论
zhangferry
zhangferry

Try this. Assuming sourcePandas is your dataframe,

  • Replace newcolumn = by f'{newcolumn}': inside sourcePandas.assign().
newcolumn = 'myColumn'
    if(newcolumn != ''):
      sourcePandas = sourcePandas.assign(**{f'{newcolumn}': sourcePandas[row['PrimaryColumn']].apply(func)})

参考文献

  1. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html
点赞
评论
放手
放手

You can pass dict
Ex.:

newcolumn = 'myColumn'
df = pd.DataFrame()
df.assign(**{newcolumn:[0,1,2]})
   myColumn
0         0
1         1
2         2

原来如此

newcolumn = 'myColumn'
    if(newcolumn != ''):
      sourcePandas = sourcePandas.assign(**{newcolumn: sourcePandas[row['PrimaryColumn']].apply(func)})
点赞
评论