基于tag/column值的python-pandas数据帧转换

2024-04-26 02:56:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下两个pandas数据帧

df1=
           selected0 selected1
2017-01-01  product1  product2
2017-01-02  product1  product2
2017-01-03  product3  product4

df2 = 
            selected0 selected1
2017-01-01       0.2       0.3
2017-01-02       0.3       0.4
2017-01-03       0.5       0.6

现在我想将这两个数据帧转换成一个单独的数据帧,如下所示

^{pr2}$

有没有一种更像python的方法可以在不遍历数据帧中的每一行的情况下做到这一点?非常感谢


Tags: 数据方法pandas情况df1df2product1pr2
2条回答

使用可怕的循环

df3 = pd.DataFrame(index=df1.index, columns=np.unique(df1.values))

for (d, c), v in df2.stack().iteritems():
    df3.set_value(d, df1.get_value(d, c), v)

df3

enter image description here

您可以将两个数据帧转换为长格式,然后根据日期合并并选择*,然后将结果转换回宽格式:

(df1.stack().to_frame("Product")               # reshape df1 to long format
    .join(df2.stack().rename("Value"))         # reshape df2 to long format and join with df1
    .reset_index(level = 1, drop = True)       # drop the original column names
    .pivot(columns="Product", values="Value")) # reshape to wide format

enter image description here

相关问题 更多 >