gpt4 book ai didi

python - 将 Pandas 切割操作转换为常规字符串

转载 作者:行者123 更新时间:2023-11-28 20:39:13 24 4
gpt4 key购买 nike

我明白了。 pandas cut 操作的输出:

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(',', ' -')

有更好的方法吗?

最佳答案

使用 pd.cutlabels 参数:

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

关于python - 将 Pandas 切割操作转换为常规字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38927585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com