我有一個df_value_bin帶有 Multiindex的 DataFrame ( ),它是分箱值,如下所示:
import pandas as pd
import numpy as np
np.random.seed(100)
df = pd.DataFrame(np.random.randn(100, 3), columns=['a', 'b', 'value'])
a_bins = np.arange(-3, 4, 1)
b_bins = np.arange(-2, 4, 2)
df['a_bins'] = pd.cut(df['a'], bins=a_bins)
df['b_bins'] = pd.cut(df['b'], bins=b_bins)
df_value_bin = df.groupby(['a_bins','b_bins']).agg({'value':'mean'})
這是快速瀏覽df_value_bin:
value
a_bins b_bins
(-3, -2] (-2, 0] -0.417606
(0, 2] -0.267035
(-2, -1] (-2, 0] -0.296727
(0, 2] -0.112280
(-1, 0] (-2, 0] 0.459780
(0, 2] 0.131588
(0, 1] (-2, 0] 0.110268
(0, 2] 0.287755
(1, 2] (-2, 0] 0.254337
(0, 2] -0.627460
(2, 3] (-2, 0] -0.075165
(0, 2] -0.589709
然后,我想在給 some和時獲得最接近value的。df_value_binab
假設 a=1.5 和 b=-1,那么我們應該得到 value=0.254337。
嘗試 1
我可以為a_binsand生成布爾掩碼b_bins:
a_test = 1.5
b_test = -1
boolean_a = df_value_bin.index.get_level_values('a_bins').categories.contains(a_test)
boolean_b = df_value_bin.index.get_level_values('b_bins').categories.contains(b_test)
print(boolean_a, boolean_b) # Output: [False False False False True False] [ True False]
但是,我不知道使用掩碼來選擇行...
嘗試 2
我可以直接獲取索引:
index_a = np.digitize(a_test, a_bins, right=True)
index_b = np.digitize(b_test, b_bins, right=True)
print(index_a, index_b) # Output: 5 1
同樣,我不知道如何使用索引直接選擇行。
筆記
似乎第二種方法應該更快,因為它使用np.digitize(). 如果您有任何想法來完成它或其他更好的方法,請隨時回答!
uj5u.com熱心網友回復:
在這種情況下,您可以只使用數字進行索引:
df_value_bin.loc[(1.5, -1)]
輸出(忽略值,隨機生成,看Name):
value 0.047439
Name: ((1, 2], (-2, 0]), dtype: float64
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389951.html
