python - 如何通过匹配字典值将二级列标题/索引添加到数据框?

标签 python python-3.x pandas dataframe

我有一个现有的数据框。

l1 | a    b    c  |  d    e    f
--------------------------------
0  | 1    1    1  |  1    1    1
1  | 1    1    1  |  1    1    1
2  | 1    1    1  |  1    1    1

还有这本字典。

{
  "a": "dog",
  "b": "dog",
  "c": "dog",
  "d": "fish",
  "e": "fish",
  "f": "fish",
}

创建第二个列级别将现有列与其字典中的类别相匹配的最简单方法是什么?

真正的列和字典要大得多,组织性也差得多。 🙃

结果应该是这样的。

l2 |     dog      |     fish
l1 | a    b    c  |  d    e    f
--------------------------------
0  | 1    1    1  |  1    1    1
1  | 1    1    1  |  1    1    1
2  | 1    1    1  |  1    1    1

最佳答案

为第一个系列添加一个额外的映射,然后使用 pd.MultiIndex.from_tuples :

d.update({'l1': 'l2'})
df.columns = pd.MultiIndex.from_tuples([(d[k], k) for k in df.columns])

print(df)

  l2 dog       fish      
  l1   a  b  c    d  e  f
0  0   1  1  1    1  1  1
1  1   1  1  1    1  1  1
2  2   1  1  1    1  1  1

关于python - 如何通过匹配字典值将二级列标题/索引添加到数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53861225/

相关文章:

python - 在python pandas中将多个列值合并为一列

python - 无法从 az cli 部署 python 应用程序

Python FTP : "ftplib.error_temp: 421 Timeout - try typing a little faster next time" error

python - 为什么 f 字符串比 str() 解析值更快?

python - Pandas :两个 datetime64 对象的差异产生 NaT 而不是正确的 timedelta 值

python - xarray - 按特定日期范围对数据进行分组

python - 将交互式 WebAgg 绘图嵌入 Tornado 时出现问题

python - 装饰器隐藏方法说明

python-3.x - 如何修复 'C extension not loaded, training will be slow. Install a C compiler and reinstall gensim for fast training.'

python - Sqlalchemy orm 根据给定输入动态查询过滤