不同长度的4级数据帧

2024-03-28 13:11:04 发布

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

我想创建一个四维层次索引的数据帧。我找到了多索引的文档

arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
           np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]

s = pd.Series(np.random.randn(8), index=arrays)

我希望我的索引有四个数组,并且它们的长度不同。我该怎么做呢?你知道吗


Tags: 数据文档foonpbarrandombazarray
1条回答
网友
1楼 · 发布于 2024-03-28 13:11:04

这实际上是一个如何表示数据的问题。 本质上,这不是一个系列,而是一个具有5列的数据帧:

例如:

df = pd.DataFrame({"level_0":{"0":"bar","1":"bar","2":"baz","3":"baz","4":"foo","5":"foo","6":"qux","7":"qux"},"level_1":{"0":"one","1":"two","2":"one","3":"two","4":"one","5":"two","6":"one","7":"two"},"level_2":{"0":"a","1":"b","2":"c","3":"d","4":"e","5":"f","6":"g","7":"h"},"level_3":{"0":"1","1":"2","2":"3","3":"4","4":"5","5":"6","6":"7","7":"8"},"0":{"0":1.7686082254,"1":-1.2237523116,"2":-1.3066335651,"3":-1.3800965009,"4":-0.5995811728,"5":-1.4717242393,"6":-1.0613097567,"7":-0.3232780637}})

你会得到:

enter image description here

然后可以将索引设置为4级索引

df = df.set_index(['level_0', 'level_1', 'level_2', 'level_3'])

你得到你的4级索引系列

enter image description here

原始数据帧可能缺少值(即,您的索引数组最初是“不同长度的”),这将提供您要查找的内容。你知道吗

相关问题 更多 >