[英]Python Pandas Groupby a List of Lists
我是Python的新手,正在嘗試將在兩個對我有用的單獨程序中創建的功能組合在一起。
目標是按各種說明對值進行分組,然后按日期對數據集的平均值進行分組。 我已經使用Pandas Groupby成功地做到了這一點。
我要評估的描述之一是在數據集中每個點的給定距離內求平均值。 到目前為止,我一直使用郵政編碼作為位置描述來對此進行近似。 另外,我已經能夠使用Geopy使用GPS點確定數據集中所需距離內的所有其他點。 這為我提供了所需距離內數據集中每個ID的ID列表。
這是一個示例數據集:
ID Date Value Color Location
1 1 1234 Red 60941
1 2 51461 Red 60941
1 3 6512 Red 60941
1 4 5123 Red 60941
1 5 48413 Red 60941
2 1 5416 Blue 60941
2 2 32 Blue 60941
2 3 18941 Blue 60941
2 4 5135 Blue 60941
2 5 1238 Blue 60941
3 1 651651 Blue 60450
3 2 1777 Blue 60450
3 3 1651 Blue 60450
3 4 1968 Blue 60450
3 5 846 Blue 60450
4 1 1689 Red 60941
4 2 1651 Red 60941
4 3 184 Red 60941
4 4 19813 Red 60941
4 5 132 Red 60941
5 1 354 Yellow 60450
5 2 684 Yellow 60450
5 3 489 Yellow 60450
5 4 354 Yellow 60450
5 5 846 Yellow 60450
這是我目前使用郵政編碼位置描述進行的Pandas代碼:
average_df = data_df['Value'].groupby([data_df['Location'],data_df['Color'],data_df['Date']]).mean()
有沒有辦法將從Geopy獲得的列表傳遞到Groupby來代替我目前擁有的['Location']組? 例如,Groupby List(ID)[列表1:(1,2,3),列表2:(3,1,5),列表3:(2,3,4)]然后是顏色和日期。
我瀏覽了Pandas文檔並搜索了該網站,但在Pandas Groupby中找不到任何使用列表的人,因此我不確定是否有可能。 也許我需要在一個numpy數組中執行此操作? 對於任何反饋,我們都表示感謝。
熊貓將輕松按布爾列表進行分組。 因此,您所需要做的就是獲取每行是否在附近的列表。 最簡單的方法是使用列表理解:
df = pandas.DataFrame({'value': [3,2,3,6,4,1], 'location': ['a', 'a', 'b', 'c', 'c', 'c']})
nearby_locations = ['a','b']
is_nearby = [(loc in nearby_locations) for loc in df['location']]
# is_nearby = [True, True, True, False, False, False]
df.groupby(is_nearby).mean()
這將輸出:
value
False 3.666667
True 2.666667
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.