根据条件替换一行中的值

时间:2021-01-18 18:47:21

标签: pandas

我正在尝试根据 2 个条件填写一列。在这种情况下,索引(时间序列)是否介于日出和日落之间,在这种情况下,我希望在名为“阳光”的新列中为 1。否则,我希望该值为零。我是 excel 中的熊猫新手所以我正在尝试这样做,可能是错误的。

df['sunlight'] = 0
mask1 = df.index > df['sunrise']
mask2 = df.index < df['sunset']
df[mask1 & mask2]
df.loc[df[mask1 & mask2],'sunlight'] = 1
df

enter image description here

<头>
索引 日出 日落 阳光
08:18:00 08:19:17 15:56:43 0
08:19:00 08:19:17 15:56:43 0
08:20:00 08:19:17 15:56:43 1
08:21:00 08:19:17 15:56:43 1
08:22:00 08:19:17 15:56:43 1

1 个答案:

答案 0 :(得分:0)

让我们以一个 DataFrame 为例,它只包含一天的数据,频率为一小时(不是分钟)。

df = pd.DataFrame({'sunrais':[pd.to_datetime('2020-01-01 08:19:17')]*24, 
                   'sunset':[pd.to_datetime('2020-01-01 15:46:43')]*24 }, 
                   index=pd.date_range('2020-01-01 00:00:00', '2020-01-01 23:00:00', freq='H')
                 )

如果现在将真值转换为整数,则可以一步将两个选择相乘。

df['sunlight'] = (df['sunrais']<df.index).astype(int) * (df.index<df['sunset']).astype(int)

输出如下:

                                sunrais              sunset  sunlight
2020-01-01 07:00:00 2020-01-01 08:19:17 2020-01-01 15:46:43         0
2020-01-01 08:00:00 2020-01-01 08:19:17 2020-01-01 15:46:43         0
2020-01-01 09:00:00 2020-01-01 08:19:17 2020-01-01 15:46:43         1
2020-01-01 10:00:00 2020-01-01 08:19:17 2020-01-01 15:46:43         1
相关问题