gpt4 book ai didi

python - Pandas 多索引 DataFrame 为每个索引添加子索引

转载 作者:行者123 更新时间:2023-12-04 08:10:40 25 4
gpt4 key购买 nike

我有一个带有“bar”和“baz”行的多索引数据框,每一行都有一行“一”和“二”。我现在想在每一行“bar”和“foo”中添加一行“三”。
有没有一种优雅的方式来做到这一点?
例如:

import pandas as pd
import numpy as np

arrays = [["bar", "bar", "baz", "baz"],
["one", "two", "one", "two"]]

tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
df = pd.DataFrame(np.random.randn(3, 4), index=["A", "B", "C"], columns=index)
In [38]: df
Out[38]:
first bar baz
second one two one two
A 0.357392 -1.880279 0.099014 1.354570
B 0.474572 0.442074 -1.173530 -1.362059
C -0.980140 -0.173440 -1.490654 -0.539123
我想要这样的东西:
first        bar                           baz                    
second one two three one two three
A -0.096890 0.012150 nan -0.749569 -0.965033 nan
B -0.854206 0.118473 nan 0.263058 -0.025849 nan
C -0.688007 -0.258569 nan 0.127305 -0.955044 nan

最佳答案

我不知道它有多像 Python,但有两种方法可以做到这一点:简单替换和使用插入。

  • 换人
  • df[('bar','three')] = np.NaN
    df[('baz','three')] = np.NaN
  • 插入
  • df.insert(2,('bar','three'),np.NaN)
    df.insert(5,('baz','three'),np.NaN)
    first bar baz
    second one two three one two three
    A -0.973338 -0.233507 NaN 0.777288 -2.282688 NaN
    B -0.377486 0.080627 NaN 0.401302 0.355696 NaN
    C 0.481056 0.651335 NaN 0.161145 1.001937 NaN

    关于python - Pandas 多索引 DataFrame 为每个索引添加子索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65983574/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com