我正在尝试将分配Column
给现有df
。具体来说,某些时间戳会被排序,但当前导出是单独的series
。我想将此附加到df
。
import pandas as pd
d = ({
'time' : ['08:00:00 am','12:00:00 pm','16:00:00 pm','20:00:00 pm','2:00:00 am','13:00:00 pm','3:00:00 am'],
'code' : ['A','B','C','A','B','C','A'],
})
df = pd.DataFrame(data=d)
df['time'] = pd.to_timedelta(df['time'])
cutoff, day = pd.to_timedelta(['3.5H', '24H'])
df.time.apply(lambda x: x if x > cutoff else x + day).sort_values().reset_index(drop=True)
x = df.time.apply(lambda x: x if x > cutoff else x + day).sort_values().reset_index(drop=True).dt.components
x = x.apply(lambda x: '{:02d}:{:02d}:{:02d}'.format(x.days*24+x.hours, x.minutes, x.seconds), axis=1)
输出:
0 08:00:00
1 12:00:00
2 13:00:00
3 16:00:00
4 20:00:00
5 26:00:00
6 27:00:00
我改变了
df['time'] = x.apply(lambda x: '{:02d}:{:02d}:{:02d}'.format(x.days*24+x.hours, x.minutes, x.seconds), axis=1)
但这产生了
time code
0 08:00:00 A
1 12:00:00 B
2 13:00:00 C
3 16:00:00 A
4 20:00:00 B
5 26:00:00 C
6 27:00:00 A
如你看到的。排序后,时间戳未与其各自的值对齐。
预期的输出是:
time code
0 08:00:00 A
1 12:00:00 B
2 13:00:00 C
3 16:00:00 C
4 20:00:00 A
5 26:00:00 B
6 27:00:00 A
从您的代码中删除reset_index(drop = True),稍后排序可能对您有用。
import pandas as pd
d = ({
'time' : ['08:00:00 am','12:00:00 pm','16:00:00 pm','20:00:00 pm','2:00:00 am','13:00:00 pm','3:00:00 am'],
'code' : ['A','B','C','A','B','C','A'],
})
df = pd.DataFrame(data=d)
df['time'] = pd.to_timedelta(df['time'])
cutoff, day = pd.to_timedelta(['3.5H', '24H'])
x = df.time.apply(lambda x: x if x > cutoff else x + day).dt.components
df['time'] = x.apply(lambda x: '{:02d}:{:02d}:{:02d}'.format(x.days*24+x.hours, x.minutes, x.seconds), axis=1)
df = df.sort_values('time')
print(df)
熊猫通过索引进行对齐。reset_index(drop = True)破坏了原始索引,并导致已排序的时间列被顺序分配回去。这可能就是为什么您没有得到什么。
原始时间栏。
0 08:00:00
1 12:00:00
2 16:00:00
3 20:00:00
4 02:00:00
5 13:00:00
6 03:00:00
在sort_values()之后。
4 02:00:00
6 03:00:00
0 08:00:00
1 12:00:00
5 13:00:00
2 16:00:00
3 20:00:00
在reset_index(drop = True)之后
0 02:00:00
1 03:00:00
2 08:00:00
3 12:00:00
4 13:00:00
5 16:00:00
6 20:00:00
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句