从多个标量值向 MultiIndex 数据框添加多列

问题描述 投票:0回答:0

给定以下 MultiIndex df

|富 | | |一个 |两个 | | ------ | ------ | | “12345” | “1235” | | “12345” | “1345”|

我想追加更多列,每个列都填充相同的值,但不同列的值不同。我将这些值按以下方式存储为 MultiIndex pandas Series se:

|酒吧| 0 | 2 | | | 1 | 3 | ………… | | 99 | 7 |

结果将如下所示: |富 | |酒吧 | | ... | | |一个 |两个 | 0 | 1 | ... | 99 | | ------ | ------ | --- | --- | ... | --- | | “12345” | “1235” | 2 | 3 | ... | 7 | | “12345” | “1345” | 2 | 3 | ... | 7 |

我发现这个非常丑陋的解决方案...

for i in range(len(se)):
    df["bar", i] = se[i]

...这也给了我一个警告:

PerformanceWarning: DataFrame is highly fragmented.  This is usually the result of calling
frame.insert
many times, which has poor performance.  Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use
newframe = frame.copy()``

一段时间以来一直在努力寻找解决方案,在此先感谢您提供有用的答案!

python python-3.x pandas dataframe multi-index
© www.soinside.com 2019 - 2024. All rights reserved.