【问题标题】:Calculate a new column with Pandas使用 Pandas 计算新列
【发布时间】:2017-02-03 20:25:28
【问题描述】:

基于this 问题,我想知道如何使用 def() 来计算 Pandas 的新列并使用多个参数(字符串和整数)?

具体例子:

df_joined["IVbest"] = IV(df_joined["Saison"], df_joined["Wald_Typ"], df_joined["NS_Cap"])

"Saison", "Wald_Typ" 是字符串 "NS_Cap" 是整数

现在我想通过这个定义运行所有这些值并再次返回一个 x 值:

def IV(saison, wald, ns):
    if saison == "Sommer":
        if wald == "Laubwald":
            x = ns * 0.1
        elif wald == "Nadelwald":
            x = ns * 0.2
        elif wald == "Mischwald":
            x = ns * 0.3
    elif saison == "Winter":
        if wald == "Laubwald":
            x = ns * 0.01
        elif wald == "Nadelwald":
            x = ns * 0.02
        elif wald == "Mischwald":
            x = ns * 0.03
    return x

我怎样才能做到最好?

我尝试过类似的东西

df_joined["IVbest"] = IV(df_joined["Saison", "Wald_Typ", "NS_Cap"])

df_joined["IVbest"] = df_joined["Saison", "Wald_Typ", "NS_Cap"].apply(IV)

但没有任何效果:(

【问题讨论】:

  • 你需要将axis=1传递给applydf_joined["IVbest"] = df_joined[["Saison", "Wald_Typ", "NS_Cap"]].apply(lambda x: IV(x["Saison"], x["Wald_Typ"], x["NS_Cap"]), axis=1)
  • 如果您将签名更改为 def IV(df): #do stuff with df['saison'], df['wald'] and df['ns'],则您的 def 可以工作,返回一个系列`
  • 谢谢埃德!你的第一个例子效果很好。如果我希望输出为整数怎么办?我可以在输出中应用类似 int(round(xy)) 的东西吗?我也一定会考虑你的其他想法!
  • 这可能有效,但这里的一般原则是避免使用循环和apply,您应该能够使用对整个 df 进行操作的矢量化方法对 df 执行操作,但我们没有不知道,因为你还没有发布你的完整代码
  • 好的,我已经发布了我的 def()。有任何想法吗?很抱歉最近有这么多问题,但我对 Pandas 很陌生,这个模块似乎很复杂

标签: python python-2.7 csv pandas


【解决方案1】:

我认为在这种情况下,最好使用 6 个掩码并使用它们仅对这些行执行计算:

sommer_laub = (df_joined['Saison'] == 'Sommer') & (df_joined['Wald_Typ'] == 'Laubwald')
sommer_nadel = (df_joined['Saison'] == 'Sommer') & (df_joined['Wald_Typ'] == 'Nadelwald')
sommer_misch = (df_joined['Saison'] == 'Sommer') & (df_joined['Wald_Typ'] == 'Mischwald')
winter_laub = (df_joined['Saison'] == 'Winter') & (df_joined['Wald_Typ'] == 'Laubwald')
winter_nadel = (df_joined['Saison'] == 'Winter') & (df_joined['Wald_Typ'] == 'Nadelwald')
winter_misch = (df_joined['Saison'] == 'Winter') & (df_joined['Wald_Typ'] == 'Mischwald')
df.loc[sommer_laub, 'IVbest'] = df.loc[sommer_laub,'NS_Cap'] * 0.1
df.loc[sommer_nadel, 'IVbest'] = df.loc[sommer_nadel,'NS_Cap'] * 0.2
df.loc[sommer_misch, 'IVbest'] = df.loc[sommer_misch,'NS_Cap'] * 0.3
df.loc[winter_laub, 'IVbest'] = df.loc[winter_laub,'NS_Cap'] * 0.01
df.loc[winter_nadel, 'IVbest'] = df.loc[winter_nadel,'NS_Cap'] * 0.02
df.loc[winter_misch, 'IVbest'] = df.loc[winter_misch,'NS_Cap'] * 0.03

【讨论】:

  • 感谢您以这种方式向我展示。但为什么会更好呢?更快还是更优雅?
  • 更快,这将只对每个掩码感兴趣的行起作用,您的方法需要查看每一行并分别评估您的布尔条件,这对于大 df 会更慢
  • 它很大,而且数据池变得越来越复杂。所以更快是好的:-)
猜你喜欢
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多