我明白了。 pandas 剪切操作的输出:
0 (0, 20]
1 (0, 20]
2 (0, 20]
3 (0, 20]
4 (0, 20]
5 (0, 20]
6 (0, 20]
7 (0, 20]
8 (0, 20]
9 (0, 20]
如何将 (0, 20] 转换为 0 - 20?
我正在做这个:
.str.replace('(', '').str.replace(']', '').str.replace(',', ' -')
还有更好的方法吗?
使用
labels
的
pd.cut
参数:
pd.cut(df['some_col'], bins=[0,20,40,60], labels=['0-20', '20-40', '40-60'])
我不知道您确切的
pd.cut
命令是什么样的,但上面的代码应该可以让您很好地了解该怎么做。
使用示例:
df = pd.DataFrame({'some_col': range(5, 56, 5)})
df['cut'] = pd.cut(df['some_col'], bins=[0,20,40,60], labels=['0-20','20-40','40-60'])
输出示例:
some_col cut
0 5 0-20
1 10 0-20
2 15 0-20
3 20 0-20
4 25 20-40
5 30 20-40
6 35 20-40
7 40 20-40
8 45 40-60
9 50 40-60
10 55 40-60
假设输出被分配给变量
cut
cut.astype(str)
删除包围
cut.astype(str).str.strip('()[]')
因为该 Series 的每个元素都是一个 pandas 区间,所以将它们转换为字符串的最佳方法是使用它们的 'left' 和 'right' 属性。
binLabels=[f"{i.left} - {i.right}" for i in intervals]