【问题标题】:How to rename the column names with another dataframe rows?如何用另一个数据框行重命名列名?
【发布时间】:2020-01-30 00:40:31
【问题描述】:

我有一个列名的数据框:df1

A_01 A_02 B_03 C_04
 0    0    0    1
 1    2    1    0
 0    1    0    3

还有,df2:

no. value
01  1103
02  1105
03  1210
04  1306

如何使用 df2 上的值重命名 df1 列,如下所示:

1103 1105 1210 1306
 0    0    0    1
 1    2    1    0
 0    1    0    3

【问题讨论】:

  • df1.columns = df2['value'].values
  • 您是否搜索过如何重命名 pandas 中的列?有一个 DataFrame.rename 特定功能,您可以查看here。您是否查看过有关如何对 pandas 数据框进行切片或获取值的文档?还有关于 here 的可用文档

标签: python pandas dataframe rename


【解决方案1】:

你需要:

df1.columns = df1.columns.str.split('_').str[1].map(df2.set_index('no.')['value'])

输出:

    1103    1105    1210    1306
0   0         0      0         1
1   1         2      1         0
2   0         1      0         3

【讨论】:

  • 谢谢,它现在可以工作了,但是如果我像这样更改值,110325。所以,我得到了错误:AttributeError: Can only use .str accessor with string values (i.e. inferred_type is 'string', 'unicode' or 'mixed')
  • 你必须把它们变成字符串。
猜你喜欢
  • 1970-01-01
  • 2018-06-06
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
相关资源
最近更新 更多