python - 将单索引数据框添加到多索引数据框,Pandas,Python
问题描述
如何将单个数据框添加到多索引数据框?例如
我的多索引数据是
Name Code Buying_Date Buying_Price Buying_Qty
Date Code
20140117 none a 1234 20170101 5 7
20170120 none b 5678 20180101 6 8
我希望将以下数据添加到“日期”=“20170120”
Name Code Buying_Date Buying_Price Buying_Qty
Code
abcd af abcd 20170101 5 7
efgh bf efgh 20180101 6 8
期望的结果是
Name Code Buying_Date Buying_Price Buying_Qty
Date Code
20140117 none a 1234 20170101 5 7
20170120 none b 5678 20180101 6 8
abcd af abcd 20170101 5 7
efgh bf efgh 20180101 6 8
提前感谢您的建议。
解决方案
您可以使用:
df = df1.append(df2.assign(Date=20170120).set_index('Date', append=True).swaplevel(0,1))
print (df)
Buying_Date Buying_Price Buying_Qty Code Code.1 Name
Date Code
20140117 none 20170101 5 7 NaN 1234.0 a
20170120 none 20180101 6 8 NaN 5678.0 b
abcd 20170101 5 7 abcd NaN af
efgh 20180101 6 8 efgh NaN bf
详情:
print (df2.assign(Date=20170120).set_index('Date', append=True).swaplevel(0,1))
Name Code Buying_Date Buying_Price Buying_Qty
Date Code
20170120 abcd af abcd 20170101 5 7
efgh bf efgh 20180101 6 8
说明:
推荐阅读
- javascript - AG-Grid React 改变 Cell Flash 的颜色
- data-structures - 如何实现具有多个根的树数据结构
- python - 在字典中创建字典以将其转换为 Json 数据
- c++ - C生成的asm调用指向错误的偏移量
- azure - 从部署作业中检索发布信息
- android - Android,在样式中设置主题不起作用
- javascript - 将日期名称转换为缩写
- dns - DNS查找在Ubuntu 20.04上的wireguard服务器(不是客户端)上不起作用
- firebase - firebase 电话授权赋予管理员角色
- excel - 将列中的文本分为两列(文本和数字) - Google 工作表或 Excel