執行以下操作后,我有以下數據框:train_X = icon[['property', 'room', 'date', 'month', 'amount']]train_frame = train_X.groupby(['property', 'month', 'date', 'room']).median()print(train_frame) amountproperty month date room 1 6 6 2 3195.000 12 3 2977.000 18 2 3195.000 24 3 3581.000 36 2 3146.000 3 3321.500 42 2 3096.000 3 3580.000 54 2 3195.000 3 3580.000 60 2 3000.000 66 3 3810.000 78 2 3000.000 84 2 3461.320 3 2872.800 90 2 3461.320 3 3580.000 96 2 3534.000 3 2872.800 102 3 3581.000 108 3 3580.000 114 2 3195.000我的目標是根據我這樣做的(房產、月份、日期、房間)跟蹤中位數金額:big_list = [[property, month, date, room], ...]test_list = [property, month, date, room]if test_list == big_list: #I want to get the median amount wrt to that row which matches the test_list我該怎么做呢?我所做的是,嘗試了以下...count = 0test_list = [2, 6, 36, 2]for j in big_list: if test_list == j: break count += 1現在,在獲得計數后,如何通過數據幀中的計數訪問中位數?他們是一種按索引訪問數據幀的方法嗎?請注意:big_list 是列表的列表,其中每個列表都是來自上述數據框的 [property, month, date, room]test_list 是與 big_list 匹配的傳入列表,以防萬一。
2 回答

收到一只叮咚
TA貢獻1821條經驗 獲得超5個贊
回答最后一個問題: 他們是按索引訪問數據幀的方法嗎?
當然有 - 你應該使用 df.iloc 還是 loc 取決于你是否想通過整數獲得純粹的(我猜是這種情況) - 你應該使用 'iloc' 或例如字符串類型索引 - 然后你可以使用 loc .
文檔: https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html
編輯:回到問題。那么,我假設“金額”是您搜索的中位數。您可以在分組數據幀上使用 reset_index() 方法,例如
train_frame_reset = train_frame.reset_index()
然后您可以再次訪問您的列名,因此您應該執行以下操作(假設 j 是找到的行的索引):
train_frame_reset.iloc[j]['amount'] <- will give you median

阿晨1998
TA貢獻2037條經驗 獲得超6個贊
如果我正確理解您的問題,您根本不需要計算,您可以直接通過 loc 訪問這些值。
看著:
A=pd.DataFrame([[5,6,9],[5,7,10],[6,3,11],[6,5,12]],columns=(['lev0','lev1','val']))
然后你做了:
test=A.groupby(['lev0','lev1']).median()
例如,訪問組 lev0=6 和 lev1 =1 的中位數可以通過以下方式完成:
test.loc[6,5]
添加回答
舉報
0/150
提交
取消