Python-如何正确使用pd.cut



我在一个名为"STREET_NO"的数据帧中有一列,我正试图在该数据帧中添加名为"BIN"的新列。我正在尝试使用pd.cut((获取"STREET_NO"(例如1290(并将其更改为1200。换句话说,对于0-300之间的街道编号,我希望新的"BIN"列显示0。对于301-600之间的街道编号,我希望"BIN"列显示300,依此类推。我的"street_NO"值范围为1-99999。目前我有:

df['BIN'] = pd.cut(x=df['STREET_NO'], bins=[0,300,600,900,1200,1500,1800,2100], labels=['0','300','600','900','1200','1500','1800']

我可以简单地在我的"箱子"one_answers"标签"中添加越来越多的数字,直到我达到最后的99999,但有更简单的方法吗?

您可以对仓位和标签使用range()函数,只需确保范围与总行数重叠即可:

import pandas as pd
df = pd.DataFrame({'STREET_NO': range(1, 100000)}) # range end is n+1 to reproduce 1-99999
df['BIN'] = pd.cut(x=df['STREET_NO'], 
bins=list(range(0, 100500, 300)), # so 99901 would be in the last bin
labels=list(range(0, 100200, 300))) # labels are bins-1
print(df.tail(300))
# Output:
STREET_NO   BIN
99599   99600       99300
99600   99601       99600
99601   99602       99600
99602   99603       99600
99603   99604       99600
...     ...         ...
99994   99995       99900
99995   99996       99900
99996   99997       99900
99997   99998       99900
99998   99999       99900
400 rows × 2 columns