通过使用新的multiindex重复一行来创建 pandas 数据框 [英] Create pandas dataframe by repeating one row with new multiindex

查看:95
本文介绍了通过使用新的multiindex重复一行来创建 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在熊猫中,我有一个系列和一个多索引:

In Pandas I have a series and a multi-index:

s = pd.Series([1,2,3,4], index=['w', 'x', 'y', 'z'])
idx = pd.MultiIndex.from_product([['a', 'b'], ['c', 'd']])

对于我来说,创建一个以idx为索引,以s为每一行的值,将S中的索引保留为列的DataFrame的最佳方法是什么?

What is the best way for me to create a DataFrame that has idx as index, and s as value for each row, preserving the index in S as columns?

df =
       w   x   y   z
a  c   1   2   3   4
   d   1   2   3   4
b  c   1   2   3   4
   d   1   2   3   4

推荐答案

使用pd.DataFrame构造函数,后跟assign

pd.DataFrame(index=idx).assign(**s)

     w  x  y  z
a c  1  2  3  4
  d  1  2  3  4
b c  1  2  3  4
  d  1  2  3  4

这篇关于通过使用新的multiindex重复一行来创建 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆