如何在索引和列的条件下更改多索引数据帧?

2024-04-26 02:57:25 发布

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

具有以下数据帧:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a':[0, 0, 1, 1],
                   'b':[0, 1, 0, 1],
                   'A':['w', 'x', 'y', 'z'],
                   'B':[True, False, True, False],
                   'C':[np.nan]*4}).set_index(['a', 'b'])

我想更改C的值,其中'a' == 0'A' == w'B' is True。你知道吗

我找到了这个解决方案:

temp = df.loc[0]
temp.loc[(temp['A'] == 'w')&(temp['B']), 'C'] = 42

装模作样已经完成了,但我得到了以下警告:

/home/me/.virtualenvs/myenv/lib/python3.6/site-packages/pandas/core/indexing.py:477: 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

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.obj[item] = s

这给出了同样的警告,并没有做作:

df.query("A == 'w' & B").loc[0, 'C'] = 42

有没有办法在没有警告的情况下对df进行更改?你知道吗


Tags: importfalsetrue警告dataframepandasdfis