我有一個帶有兩級分層索引的 Pandas DataFrame。我想根據從某個子集到不同子集的條件設定一個值。
我認為這最好用一個小例子來解釋:
import numpy as np
import pandas as pd
example = pd.DataFrame({'ind_1': 5*[0] 5*[1], 'ind_2': np.concatenate([np.arange(5), np.arange(5)]),
'col_1': np.random.random(size=10), 'col_2': np.random.random(size=10)})
example = example.set_index(['ind_1', 'ind_2'])
example_0 = example.loc[0]
example_1 = example.loc[1]
example['condition'] = False
condition = example_1['col_1'] > 0.5
與資料幀
$ example
col_1 col_2 condition
ind_1 ind_2
0 0 0.430966 0.064335 False
1 0.631710 0.313696 False
2 0.354766 0.479626 False
3 0.548612 0.793249 False
4 0.144033 0.352583 False
1 0 0.586365 0.578001 False
1 0.306403 0.399591 False
2 0.312621 0.439042 False
3 0.010637 0.232054 False
4 0.762034 0.293433 False
$ example_0
col_1 col_2
ind_2
0 0.430966 0.064335
1 0.631710 0.313696
2 0.354766 0.479626
3 0.548612 0.793249
4 0.144033 0.352583
$ example_1
col_1 col_2
ind_2
0 0.586365 0.578001
1 0.306403 0.399591
2 0.312621 0.439042
3 0.010637 0.232054
4 0.762034 0.293433
$ condition
ind_2
0 True
1 False
2 False
3 False
4 True
現在我想分配一個值如下
example.loc[0].loc[condition] = True
這導致(理所當然地)導致 aSettingWithCopyWarning并且在更復雜的情況下根本不起作用。
預期的輸出將是
$ example
col_1 col_2 condition
ind_1 ind_2
0 0 0.430966 0.064335 True
1 0.631710 0.313696 False
2 0.354766 0.479626 False
3 0.548612 0.793249 False
4 0.144033 0.352583 True
1 0 0.586365 0.578001 False
1 0.306403 0.399591 False
2 0.312621 0.439042 False
3 0.010637 0.232054 False
4 0.762034 0.293433 False
所以為ind_1 == 0我們設定條件。但請注意,條件是為ind_1 == 1
這樣做的最干凈方法是什么?
uj5u.com熱心網友回復:
您可以reindex在condition隨后通過numpy的陣列:
example.loc[0, 'condition'] = condition.reindex(example.loc[0].index).values
請注意,您沒有分配鏈索引,即.loc[].loc[],而是執行.loc[ind, column].
輸出:
col_1 col_2 condition
ind_1 ind_2
0 0 0.295983 0.241758 False
1 0.707799 0.765772 True
2 0.822369 0.062530 True
3 0.816543 0.621883 False
4 0.048521 0.738549 True
1 0 0.433304 0.527344 False
1 0.727886 0.557176 False
2 0.653163 0.686719 False
3 0.020094 0.887114 False
4 0.777072 0.506128 False
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/383052.html
