【问题标题】:using recently created attributes in pandas dataframe to create new attribute使用熊猫数据框中最近创建的属性来创建新属性
【发布时间】:2018-05-31 08:39:01
【问题描述】:

我正在寻找 R 的 mutate 的等价物,它允许您在创建变量后立即引用它们在同一个 mutate 调用中

new_df <- old_df %>%
    mutate(new_col = ifelse(something, 0, 1),
           newer_col = ifelse(new_col == 0, 'yay', 'nay'))

在 python pandas 中寻找等价物。

如果我创建以下数据框,我想知道是否有办法使用.assign 来做同样的事情?

dic = {'names': ['jeff', 'alice', 'steph', 'john'],
       'numbers':[4, 6, 5, 7]}

df = pd.DataFrame(dic)

df = df.assign(less_than_6 = np.where(df.numbers < 6, 100, 0),
               pass_fail = np.where(df.less_than_6 == 100, 'pass', 'fail'))

我能想到的替代方案是..

df['less_than_6'] = np.where(df.numbers < 6, 100, 0)
df['pass_fail'] = np.where(df.less_than_6 == 100, 'pass', 'fail')

但想知道是否有办法在同一个调用中做到这一点?

【问题讨论】:

  • 不起作用。我得到了和以前一样的'DataFrame' object has no attribute 'less_than_6'。谢谢你的尝试!
  • 将其添加为答案

标签: python r pandas dataframe dplyr


【解决方案1】:

assign 中使用dict

df.assign(**{'less_than_6' :lambda x : np.where(x['numbers'] < 6, 100, 0)}).assign(**{'pass_fail':lambda x : np.where(x['less_than_6'] == 100, 'pass', 'fail')})                                                            
Out[202]: 
   names  numbers  less_than_6 pass_fail
0   jeff        4          100      pass
1  alice        6            0      fail
2  steph        5          100      pass
3   john        7            0      fail

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-12-10
  • 2021-12-21
  • 1970-01-01
  • 2016-08-28
  • 2021-05-15
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多