重命名 Pandas 列的数值

huangapple go评论56阅读模式
英文:

Rename Pandas column values

问题

我有一个像这样的pandas数据框

列1 列2
1 a
2 a
3 b
4 c
5 d

我想把列2命名为:

列1 列2
1 行1
2 行1
3 行2
4 行3
5 行4

我正在尝试一些硬编码的方法,比如重命名每一列,但在实际操作中,我有很多行,所以硬编码是不可行的,有没有什么函数或者Python的方法可以帮我完成同样的任务?

英文:

I have pandas dataframe like this

Column 1 Column 2
1 a
2 a
3 b
4 c
5 d

I want to name the column 2 as:

Column 1 Column 2
1 row1
2 row1
3 row2
4 row3
5 row4

I am trying the ways that are hard coded, like renaming each column, but in practice I have lots of rows so hard coding is not possible, is there any function or something python that can do the same task for me?

答案1

得分: 2

让我们尝试 Series.factorize

df['Column2'] = (pd.Series(df['Column2'].factorize()[0])
                 .add(1).astype(str).radd('row'))
print(df)

   Column1 Column2
0        1    row1
1        2    row1
2        3    row2
3        4    row3
4        5    row4
英文:

Let's try Series.factorize

df['Column2'] = (pd.Series(df['Column2'].factorize()[0])
                 .add(1).astype(str).radd('row'))
print(df)

   Column1 Column2
0        1    row1
1        2    row1
2        3    row2
3        4    row3
4        5    row4

huangapple
  • 本文由 发表于 2023年2月6日 13:31:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定