【问题标题】:Setting 1 or 0 to new Pandas column conditionally [duplicate]有条件地将 1 或 0 设置为新的 Pandas 列[重复]
【发布时间】:2016-01-04 05:26:04
【问题描述】:

一个非常简单的熊猫问题:

如果我有这样的数据框:

   hour
 0  0
 1  1
 2  1
 3  2
 4  2
  ...

我想创建一个新列“lunch”,如果 11

【问题讨论】:

  • 你是什么意思 11
  • @anand 猜测,hour 是 12 小时内的读数,所以它应该环绕。但如果无法检查上午/下午或日期,那么它总是正确的。

标签: python pandas


【解决方案1】:

您可以采用矢量化方法(减号运算符用于否定布尔掩码):

df['lunch'] = (-df.hour.isin(range(2,11))).astype(int)

Out[368]:
   hour  lunch
0     0      1
1     1      1
2     1      1
3     2      0
4     2      0

【讨论】:

    【解决方案2】:

    试试:

    >>> df['lunch']=df['hour'].apply(lambda x: 1 if x >= 11 or x <= 1 else 0)
    >>> df
       hour  lunch
    0     0      1
    1     1      1
    2     1      1
    3     2      0
    4     2      0
    

    【讨论】:

      【解决方案3】:

      你可以

      In [231]: df['lunch'] = (df['hour']<=11) & (df['hour']<=1)
      
      In [232]: df['lunch']
      Out[232]:
      0     True
      1     True
      2     True
      3    False
      4    False
      Name: lunch, dtype: bool
      
      In [233]: df['lunch'].astype(int)
      Out[233]:
      0    1
      1    1
      2    1
      3    0
      4    0
      Name: lunch, dtype: int32
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-16
        • 2023-03-27
        • 1970-01-01
        • 2018-03-12
        • 1970-01-01
        • 1970-01-01
        • 2016-11-23
        相关资源
        最近更新 更多