【问题标题】:Pandas: count number of times between specific range熊猫:计算特定范围之间的次数
【发布时间】:2022-12-01 05:15:37
【问题描述】:
我有一个零件号数据集,对于每个零件号,它们都在特定的循环计数时被替换。例如,下表是我的数据示例,第一列是零件编号,第二列是它被替换的循环计数(即:零件 abc 在 100 个循环时被替换,然后在 594 时再次替换,然后在 1230 和 2291):
| Part # |
Cycle Count |
| abc |
100 |
| abc |
594 |
| abc |
1230 |
| abc |
2291 |
| def |
329 |
| def |
2001 |
| ghi |
1671 |
| jkl |
29 |
| jkl |
190 |
| mno |
700 |
| mno |
1102 |
| pqr |
2991 |
有了这些数据,我试图创建一个新表来计算某个零件在特定周期范围内被更换的次数,并创建一个如下例所示的表:
| Part # |
Cycle Count Range (1-1000) |
Cycle Count Range (1001-2000) |
Cycle Count Range (2001-3000) |
| abc |
2 |
1 |
1 |
| def |
1 |
0 |
1 |
| ghi |
0 |
1 |
0 |
| jkl |
2 |
0 |
0 |
| mno |
1 |
1 |
0 |
| pqr |
0 |
0 |
1 |
我尝试在 SQL 中执行此操作,但我不够熟练。
【问题讨论】:
标签:
python
sql
pandas
dataframe
【解决方案1】:
我们可以使用 np.arange 创建一些 Cycle Count Range bin 和 pd.cut 将 Cycle Count 的值分配给所述 bin。
from io import StringIO
import numpy as np
import pandas as pd
df = pd.read_csv(StringIO("""Part # Cycle Count
abc 100
abc 594
abc 1230
abc 2291
def 329
def 2001
ghi 1671
jkl 29
jkl 190
mno 700
mno 1102
pqr 2991"""), sep="\t+")
# make bins of size 1_000 using numpy.arange
bins = np.arange(0, df["Cycle Count"].max()+1_000, step=1_000)
# bin the Cycle Count series
df["Cycle Count Range"] = pd.cut(df["Cycle Count"], bins, retbins=False)
# count the Cycle Counts within the Part #/Cycle Count Range groups
out = df.pivot_table(
values="Cycle Count",
index="Part #",
columns="Cycle Count Range",
aggfunc="count"
)
print(out)
Cycle Count Range (0, 1000] (1000, 2000] (2000, 3000]
Part #
abc 2 1 1
def 1 0 1
ghi 0 1 0
jkl 2 0 0
mno 1 1 0
pqr 0 0 1
【解决方案2】:
使用crosstab 和interval_range:
#This is number of periods
p = math.ceil((df['Cycle Count'].max() - df['Cycle Count'].min())/1000)
#These are bins in which pd.cut needs to cut the series into
b = pd.interval_range(start=1, freq=1000, periods=p, closed='left')
#Then cut the series
df['Cycle Count Range'] = pd.cut(df['Cycle Count'], b)
#Do a crosstab to compute the aggregation.
out = pd.crosstab(df['Part#'], df['Cycle Count Range'])
打印出):
Cycle Count Range [1, 1001) [1001, 2001) [2001, 3001)
Part#
abc 2 1 1
def 1 0 1
ghi 0 1 0
jkl 2 0 0
mno 1 1 0
pqr 0 0 1