熊猫:' on' /' off'

时间:2017-07-22 13:59:42

标签: python pandas dataframe

我有一个数据框:

data=[
{ "event" : "A" , "time" :  "2001-03-31 22:53:22"  , "on/off" :  "on" },
{ "event" : "B" , "time" :  "2001-03-31 22:53:30"  , "on/off" :  "on" },
{ "event" : "C" , "time" :  "2001-04-01 01:32:15"  , "on/off" :  "on" },
{ "event" : "A" , "time" :  "2001-04-01 01:32:18"  , "on/off" : "off" },
{ "event" : "B" , "time" :  "2001-04-01 03:51:32"  , "on/off" : "off" },
{ "event" : "A" , "time" :  "2001-04-01 03:51:33"  , "on/off" :  "on" },
{ "event" : "C" , "time" :  "2001-04-01 04:01:07"  , "on/off" : "off" },
{ "event" : "A" , "time" :  "2001-04-01 04:29:25"  , "on/off" : "off" }]

df = pd.DataFrame(data)
df['time'] = pd.to_datetime(df['time'])

"上"激活活动和"关闭"停用它 我想每次加1:

  • 事件设置为

每次都加0:

  • 该活动已启用
  • 事件未激活

我希望输出为:

                      A     B       C
2001-03-31 22:53:22   1     0       0
2001-03-31 22:53:30   1     1       0
2001-04-01 01:32:15   1     1       1
2001-04-01 01:32:18   0     1       1
2001-04-01 03:51:32   0     0       1
2001-04-01 03:51:33   1     0       1
2001-04-01 04:01:07   1     0       0
2001-04-01 04:29:25   0     0       0

我非常确定这种技巧有一种优雅的方法

1 个答案:

答案 0 :(得分:1)

dictmap on替换offNaN

然后pivot并首先将ffill替换为NaNfillna正向填充),然后应用fillna替换ffillastype转换为int且最后转换为df['on/off'] = df['on/off'].map({'on':1, 'off':0}) df = df.pivot(index='time', columns='event', values='on/off').ffill().fillna(0).astype(int) print (df) event A B C time 2001-03-31 22:53:22 1 0 0 2001-03-31 22:53:30 1 1 0 2001-04-01 01:32:15 1 1 1 2001-04-01 01:32:18 0 1 1 2001-04-01 03:51:32 0 0 1 2001-04-01 03:51:33 1 0 1 2001-04-01 04:01:07 1 0 0 2001-04-01 04:29:25 0 0 0 的s:

 <system.web>
   <customErrors mode="On"></customErrors>
 </system.web>