我有一个数据框:
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
我非常确定这种技巧有一种优雅的方法
答案 0 :(得分:1)
dict
可map
on
替换off
和NaN
。
然后pivot
并首先将ffill
替换为NaN
(fillna
正向填充),然后应用fillna
替换ffill
由astype
转换为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>