【问题标题】:Creating a new column in a pandas csv file through conditions通过条件在 pandas csv 文件中创建新列
【发布时间】:2017-08-31 10:21:23
【问题描述】:

我已经彻底搜索了几个小时来寻找答案,但不幸的是我找不到任何东西。

我有一个 csv 文件,如图所示。

我想要做的是,例如,创建一个新列,其中每一行都是 0,除非月 ==1 and day>11。我做了类似的事情,当小时>8 和小时

dataTest['day_or_night'] = 0

dataTest['day_or_night'][dataTest['hour'] < 8] = 1

dataTest['day_or_night'][dataTest['hour'] > 20] = 1

任何帮助将不胜感激!

【问题讨论】:

    标签: python csv pandas indexing


    【解决方案1】:

    试试这个:

    df['new'] = np.where((df.month==1) & (df.day>11), 1 0)
    

    【讨论】:

      【解决方案2】:

      1 的条件布尔表达式转换为int

      dataTest['day_or_night'] = (
          dataTest.day.gt(11) & dataTest.month.eq(1)
      ).astype(np.uint8)
      

      【讨论】:

      • 这非常有效。只是另一个问题:是否有可能以某种方式添加更多条件?我试过df['ispitna'] = ( (df.day.gt(11) &amp; df.month.eq(1)) or (df.day.lw(3) &amp; df.month.eq(2)) or (df.day.gt(26) &amp; df.month.eq(3)) or (df.day.lw(3) &amp; df.month.eq(4)) or (df.day.gt(16)&amp; df.month.eq(5)) ).astype(np.uint8),但很明显,它不起作用......
      • @saremisona 是的,这应该可行……我不能保证你的逻辑。但这个想法是合理的。
      • 我不断收到同样的错误。ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
      • @saremisona 我的错,我应该看到的。不要使用or。使用|df['ispitna'] = ( (df.day.gt(11) &amp; df.month.eq(1)) | (df.day.lw(3) &amp; df.month.eq(2)) | (df.day.gt(26) &amp; df.month.eq(3)) | (df.day.lw(3) &amp; df.month.eq(4)) | (df.day.gt(16)&amp; df.month.eq(5)) ).astype(np.uint8)
      • 像魅力一样工作。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      相关资源
      最近更新 更多