gpt4 book ai didi

python - 将 pandas 列编码为分类值

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:54 24 4
gpt4 key购买 nike

我有一个数据框如下:

d = {'item': [1, 2,3,4,5,6], 'time': [1297468800, 1297468809, 12974688010, 1297468890, 1297468820,1297468805]}
df = pd.DataFrame(data=d)

df 的输出如下:

   item         time
0 1 1297468800
1 2 1297468809
2 3 1297468801
3 4 1297468890
4 5 1297468820
5 6 1297468805

这里的时间是以unix系统时间为准。我的目标是替换数据框中的 time 列。

比如

mintime = 1297468800
maxtime = 1297468890

我想把时间分成10(可以通过使用20个间隔等参数来改变)间隔,并重新编码df<中的time。比如

   item         time
0 1 1
1 2 1
2 3 1
3 4 9
4 5 3
5 6 1

既然我有数十亿条记录,那么最有效的方法是什么?谢谢

最佳答案

您可以使用 pd.cutnp.linspace 来指定 bin。这将对您的列进行分类编码,然后您可以从中按顺序提取代码:

bins = np.linspace(df.time.min() - 1, df.time.max(), 10)
df['time'] = pd.cut(df.time, bins=bins, right=True).cat.codes + 1
df

item time
0 1 1
1 2 1
2 3 1
3 4 9
4 5 3
5 6 1

或者,根据你如何处理区间边缘,你也可以这样做

bins = np.linspace(df.time.min(), df.time.max() + 1, 10)
pd.cut(df.time, bins=bins, right=False).cat.codes + 1

0 1
1 1
2 1
3 9
4 2
5 1
dtype: int8

关于python - 将 pandas 列编码为分类值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54845449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com