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

时间:2017-02-01 17:20:04

标签: python pandas

使用以下数据框:

<input type='button' ...

我想更改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 进行更改?

1 个答案:

答案 0 :(得分:1)

这可以在不发出警告的情况下发挥作用。

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