将pandas剪切操作转换为常规字符串

use*_*827 2 python pandas

我得到了foll.大熊猫切割操作的输出:

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]
Run Code Online (Sandbox Code Playgroud)

如何将(0,20)转换为0-20?

我这样做:

.str.replace('(', '').str.replace(']', '').str.replace(',', ' -')
Run Code Online (Sandbox Code Playgroud)

有更好的方法吗?

roo*_*oot 6

使用labels参数pd.cut:

pd.cut(df['some_col'], bins=[0,20,40,60], labels=['0-20', '20-40', '40-60']) 
Run Code Online (Sandbox Code Playgroud)

我不知道你的确切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'])
Run Code Online (Sandbox Code Playgroud)

示例输出:

    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
Run Code Online (Sandbox Code Playgroud)


piR*_*red 5

假设输出被分配给一个变量cut

cut.astype(str)
Run Code Online (Sandbox Code Playgroud)

删除包围

cut.astype(str).str.strip('()[]')
Run Code Online (Sandbox Code Playgroud)