访问loc中的列值会出现错误“'Series'对象是可变的,因此不能散列”

2024-09-19 20:49:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含两列感兴趣的数据帧,station和{},其中一个大厅有多个站点。我想过滤数据帧,这样我就只为每个大厅保留某些站点。在

因此,对于dataframe中的每一行,仅当hall == A and station in [A1, A2, A3] or hall == B and station in [B1, B3, B5] or ....时才保留它

举个例子,如果这是开始测向

Date   Meal   Hall     Station      Food
04/10  lunch  de neve  the grill    pizza
04/10  lunch  de neve  the kitchen  burger
04/10  lunch  covel    the oven     hot dog
04/10  lunch  covel    the kitchen  pasta

我只想保留the grill给德内夫,而{}留给科维尔,我最后应该

^{pr2}$

我创建了一本字典,记录了我想为每个大厅保留的电台

essential_stations = 
    {'HallA': [station1, station2],
     'HallB': [station3, station4],
     'HallC': [station5, station6],
    }

但是当我执行以下操作时

summary_food_df = food_df[food_df['station'].isin(essential_stations[food_df['hall']])]

我知道错误了

'Series' objects are mutable, thus they cannot be hashed

有没有其他方法可以用字典过滤掉多余的电台?在


Tags: orandthe数据indf站点food
1条回答
网友
1楼 · 发布于 2024-09-19 20:49:19
df = pd.DataFrame({'Date': {0: '04/10', 1: '04/10', 2: '04/10', 3: '04/10'},
 'Food': {0: 'pizza', 1: 'burger', 2: ' hot dog', 3: 'pasta'},
 'Hall': {0: 'de neve', 1: 'de neve', 2: 'covel', 3: 'covel'},
 'Meal': {0: 'lunch', 1: 'lunch', 2: 'lunch', 3: 'lunch'},
 'Station': {0: 'the grill',
  1: 'the kitchen',
  2: 'the oven',
  3: 'the kitchen'}})
essential_stations = {'de neve': ['the grill'], 'covel': ['the oven']}
# user apply to filter rows which satisfiy the condition (only certain stations for a hall)
df.apply(lambda x: x if x.Station in essential_stations.get(x.Hall) else np.nan, axis=1).dropna()
Out[265]: 
    Date      Food     Hall   Meal    Station
0  04/10     pizza  de neve  lunch  the grill
2  04/10   hot dog    covel  lunch   the oven

相关问题 更多 >