Skip to main content
 首页 » 编程设计

python之在 Pandas 中操作多索引列

2025年05月04日1552php

我在 Pandas 中有一个简单的多索引数据框。我正在尝试添加额外的子列,但我被

警告了
SettingWithCopyWarning:  
A value is trying to be set on a copy of a slice from a DataFrame. 
Try using .loc[row_indexer,col_indexer] = value instead 

我无法获得正确的索引咒语来完成这项工作。

附加一个代码片段,其中包含我要添加的各种列的简单、非分层示例。然后我有一个分层示例,其中我演示了如何添加新的顶级列,但无法正确操作各个子列

import pandas as pd 
import numpy as np 
 
 
#simple example that works: add two columns to a non-hierarchical frame 
sdf = pd.DataFrame(np.random.randn(6,4),columns=list('ABCD')) 
sdf['E'] = 7 
sdf['F'] = sdf['A'].diff(-1) 
 
 
#hierarchical example 
df = pd.DataFrame({('co1', 'price'): {0: 1, 1: 2, 2:12, 3: 14, 4: 15},\ 
('co1', 'size'): {0: 1, 1: 5, 2: 9, 3: 13, 4: 17},\ 
('co2', 'price'): {0: 2, 1: 6, 2: 10, 3: 14, 4: 18},\ 
('co2', 'size'): {0: 3, 1: 7, 2: 11, 3: 15, 4: 19}}) 
 
df.index.names = ['run'] 
df.columns.names = ['security', 'characteristic'] 
 
#I can add a new top level column 
df['newTopLevel?'] = "yes" 
 
 
#I cannot manipulate values of existing sub-level columns 
"""A value is trying to be set on a copy of a slice from a DataFrame. 
Try using .loc[row_indexer,col_indexer] = value instead""" 
 
df['co1']['size'] = "gross" 
df['co1']['price'] = df['co1']['price']*2 
 
 
#I cannot add a new sub-level column 
df['co1']['new_sub_col'] = "fails" 

我似乎缺少对这个问题的一些基本理解,这令人沮丧,因为我已经非常仔细地阅读了 pandas 作者编写的 O'Reilly “Python for Data Analysis”一书!呃。

请您参考如下方法:

要避免警告/错误,请使用 loc 并在一次作业中执行这些操作:

In [11]: df.loc[:, ('co1', 'size')] = "gross" 
 
In [12]: df.loc[:, ('co1', 'price')] *= 2 
 
In [13]: df.loc[:, ('co1', 'new_sub_col')] = "fails"  # not anymore 
 
In [14]: df 
Out[14]: 
security         co1          co2      newTopLevel?         co1 
characteristic price   size price size              new_sub_col 
run 
0                  2  gross     2    3          yes       fails 
1                  4  gross     6    7          yes       fails 
2                 24  gross    10   11          yes       fails 
3                 28  gross    14   15          yes       fails 
4                 30  gross    18   19          yes       fails