python - 根据对 Dataframe 的查找将列替换为多级列
问题描述
如何替换此单列标题:
foo bar
0 0 0
1 0 0
要获得这些多级列:
A B
a b
0 0 0
1 0 0
基于此数据帧映射
col1 col2 col3
0 foo a A
1 bar b B
2 baz c C
我正在尝试一个列表理解,试图创建一个新的多级列索引,但似乎没有工作......我觉得有一种更 Python 的方式来实现这一点
df1 = pd.DataFrame({'foo':[0,0],
'bar':[0,0]})
df2 = pd.DataFrame({'col1':['foo','bar','baz'],
'col2':['A','B','C'],
'col3':['a','b','c']})
df1.columns = [(df2.loc[df2['col1']==i,'col2'], df2.loc[df2['col1']==i,'col3']) for i in df1.columns]
解决方案
您可以将 df2 转换为一系列元组并将其映射到列:
df1.columns = df1.columns.map(df2.set_index('col1').apply(tuple, axis=1))
输出:
A B
a b
0 0 0
1 0 0
推荐阅读
- awk - 如何使用 Awk 对包含逗号数据的选项卡文件的列进行求和和排序
- javascript - 使用 http.get 请求初始化变量后未定义变量
- python - 如何重命名 pvlib 以导入多个版本?
- linux - 如何从 bash 检查 Linux CPU 使用情况?
- javascript - 如何在 JavaScript 中对表情符号进行 base64 编码?
- android - 房间选择表达式
- javascript - 使用 json 链接到字符串
- javascript - Uploadcare - 如何设置图片 URL 的值?
- angular - Angular 6 - 材质单选按钮和材质输入
- reactjs - 为什么我不能在 react native _ react-native-router-flux 中直接从一个场景移动到另一组场景中的另一个场景