Pandas 如何使用pd.cut() - python

这是代码段:

test = pd.DataFrame({'days': [0,31,45]})
test['range'] = pd.cut(test.days, [0,30,60])

输出:

    days    range
0   0       NaN
1   31      (30, 60]
2   45      (30, 60]

我很惊讶0不在(0,30]中,我应该怎么做才能将0归类为(0,30]?

参考方案

test['range'] = pd.cut(test.days, [0,30,60], include_lowest=True)
print (test)
   days           range
0     0  (-0.001, 30.0]
1    31    (30.0, 60.0]
2    45    (30.0, 60.0]

看区别:

test = pd.DataFrame({'days': [0,20,30,31,45,60]})

test['range1'] = pd.cut(test.days, [0,30,60], include_lowest=True)
#30 value is in [30, 60) group
test['range2'] = pd.cut(test.days, [0,30,60], right=False)
#30 value is in (0, 30] group
test['range3'] = pd.cut(test.days, [0,30,60])
print (test)
   days          range1    range2    range3
0     0  (-0.001, 30.0]   [0, 30)       NaN
1    20  (-0.001, 30.0]   [0, 30)   (0, 30]
2    30  (-0.001, 30.0]  [30, 60)   (0, 30]
3    31    (30.0, 60.0]  [30, 60)  (30, 60]
4    45    (30.0, 60.0]  [30, 60)  (30, 60]
5    60    (30.0, 60.0]       NaN  (30, 60]

或使用 numpy.searchsorted ,但days的值无需排序:

arr = np.array([0,30,60])
test['range1'] = arr.searchsorted(test.days)
test['range2'] = arr.searchsorted(test.days, side='right') - 1
print (test)
   days  range1  range2
0     0       0       0
1    20       1       0
2    30       1       1
3    31       2       1
4    45       2       1
5    60       2       2

python :安装 python 后,如何导入 Pandas - python

我已经安装了 python 。现在,当我尝试跑步时import pandas as pd 我收到以下错误Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import pandasFile ImportError: …

Python Pandas检查数据框是否不为空 - python

我有一个if语句,它在其中检查数据框是否为空。我的操作方式如下:if dataframe.empty: pass else: #do something 但实际上我需要:if dataframe is not empty: #do something 我的问题是-是否有一种.not_empty()方法可以实现这一目标?我还想问一下第二个版本在性能方面是否更好…

Python Pandas:按分组分组,平均? - python

我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…

Python Pandas:在多列上建立布尔索引 - python

尽管至少有关于如何在Python的pandas库中为DataFrame编制索引的two good教程,但我仍然无法在一个以上的列上找到一种优雅的SELECT编码方式。>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) >…

重命名默认ID python - python

我想连接两个dataFrames,但是两个数据具有不同的ID,所以结果是错误的这是我的代码data=pd.DataFrame(df.columns) data1=data.drop(axis=1,index=[0,1,2,3]).transpose() data1 这是dataframe1另一个数据框:y=sma_algo(df.loc['H+L&…