gpt4 book ai didi

python - 在我现有的 Pandas 数据框中添加一个新列

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:19 25 4
gpt4 key购买 nike

原始数据框是

column_one
1
1
1
45
45
55
55
56

Expected Output
column-new
i_1
i_1
i_1
i_2
i_2
i_3
i_3
i_4

基于 Column-1,我想在我的数据框中添加另一个新列。如果有连续值而不是添加具有相同索引的“i”。提前谢谢你。

最佳答案

你可以使用 pd.factorize .来自文档:

Useful for obtaining a numeric representation of an array when all that matters is identifying distinct values.

因此它将遇到的每个新值编码为枚举类型。之后,您只需将 'i_' 前缀添加到 new_col:

df['new_col'] = (df.col1.factorize()[0] + 1).astype(str)
df['new_col'] = 'i_' + df.new_col

输出

    col1 new_col
0 1 i_1
1 1 i_1
2 1 i_1
3 45 i_2
4 45 i_2
5 55 i_3
6 55 i_3
7 56 i_4

关于python - 在我现有的 Pandas 数据框中添加一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54628504/

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