【问题标题】:Pandas DataFrames If else condition on multiple columns containing dash [duplicate]Pandas DataFrames If else条件包含破折号的多列[重复]
【发布时间】:2020-08-15 06:50:46
【问题描述】:

请注意,我只想使用“熊猫”。我不想使用 lambda 或 NumPy。

我有一个如下图所示的数据框

import pandas as pd

df = pd.DataFrame({
    "first-name": ["john","peter","john","alex"],
    "height-ft": [6,5,4,6],
    "shape-type": ["null","null","null","null"]
})

我想申请这个

If first-name == john and height-ft == 6 
           return shape-type = good 
else if height-ft == 4
       return shape-type = bad 
else  
       change the shape-type to middle

所以最终的 Dataframe 应该是这样的

  df = ({
        "first-name": ["john","peter","john","alex"],
        "height-ft": [6,5,4,6],
        "shape-type": ["good","middle","bad","middle"]
    })

【问题讨论】:

  • 这不是你两天前here问的同一个问题吗?
  • 亲爱的@Ben.T 感谢您的回答,但这个不同,因为对于过去的问题我无法得到答案,因为所有答案都使用 NumPy 并且列名没有破折号所以我不能解决问题
  • 我无法想象你可以拥有 df 而不能使用 numpy。
  • lambda 只是 Python 中的一个未命名函数,而 numpypandas 的必需库,因此这些对答案的限制非常奇怪

标签: python pandas dataframe conditional-statements


【解决方案1】:

没有numpy,你可以这样做:

df.loc[(df['first-name'] == 'john') & (df['height-ft'] == 6), 'shape-type'] = 'good'
df.loc[(df['height-ft'] == 4), 'shape-type'] = 'bad'
df.loc[((df['first-name'] != 'john') & (df['height-ft'] != 4)), 'shape-type'] = 'middle'
print(df)

  first-name  height-ft shape-type
0       john          6       good
1      peter          5     middle
2       john          4        bad
3       alex          6     middle

np.where:

df['shape-type'] = np.where((df['first-name']=='john') & (df['height-ft']==6), 'good', 'middle')
df['shape-type'] = np.where((df['height-ft']==4), 'bad', df['shape-type'])

  first-name  height-ft shape-type
0       john          6       good
1      peter          5     middle
2       john          4        bad
3       alex          6     middle

【讨论】:

  • 非常感谢您的回答。您能否使用 np.where 添加另一个答案?
  • 检查编辑的答案
  • 谢谢@NYC Coder。我写了这段代码,但它不起作用。请您纠正一下好吗?将 numpy 导入为 np cond1=df.first-name.eq('john')&df.height-ft.eq(6) cond2=df.height-ft.eq(4) df['shape-type']=np .select([cond1,cond2],[['good'],'bad'],'middle') df
  • 更正代码:cond1=df['first-name'].eq('john') & df['height-ft'].eq(6) cond2=df['height-ft'].eq(4) df['shape-type']=np.select([cond1,cond2],[['good'],'bad'],'middle') print(df)
  • 这行得通吗?如果是,您可以将此标记为答案
【解决方案2】:
In [183]: df['shape-type'] = "middle"

In [184]: df.loc[(df['first-name'] == 'john') & (df['height-ft'] == 6), 'shape-type'] = "good"

In [185]: df.loc[df['height-ft'] == 4, 'shape-type'] = "bad"

In [186]: df
Out[186]:
  first-name  height-ft shape-type
0       john          6       good
1      peter          5     middle
2       john          4        bad
3       alex          6     middle

【讨论】:

    【解决方案3】:

    您还可以使用 iterrows() 执行一个函数,该函数将遍历 df 的所有行,然后您可以应用一个函数。

    import pandas as pd
    
    df = pd.DataFrame({
        "first_name": ["john","peter","john","alex"],
        "height_ft": [6,5,4,6],
        "shape_type": ["null","null","null","null"]
    })
    
    print(df)
    
    def define_shape_type(first_name, height_ft) :
        if first_name == 'john' and height_ft == 6 :
            return "good" 
        elif height_ft == 4 :
            return "bad" 
        else :
            return "middle"
    
    for index, row in df.iterrows():
        df.set_value(index, "shape_type", define_shape_type(row.first_name, row.height_ft))
    
    print(df)
    

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 2021-10-01
      • 2019-12-15
      • 1970-01-01
      • 2012-12-12
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多