python - 在 .loc[] 中使用 DataFrame 值
问题描述
我想以这种方式过滤 DataFrame,基于字典值。
dict = {
101 : 2500,
102 : 2700,
103 : 2000,
}
和一个这样的DataFrame:
编号 | match_id | 类型名称 | 第二 |
---|---|---|---|
1 | 101 | 经过 | 2400 |
2 | 101 | 射击 | 2450 |
3 | 101 | 比赛结束 | 2500 |
4 | 102 | 经过 | 2700 |
5 | 102 | 比赛结束 | 2600 |
6 | 103 | 比赛结束 | 2000 |
我想要一行代码返回match_id
值,其中type_name==Match_end
和second
等于字典中的值,其中键具有相同的 match_id 值。
在这种情况下,我想返回这个列表:[101,103]
因为,在 DataFrame 内部,第 3 行和第 6 行遵守条件(5 否,因为它的second
值与 不同dict.get(102)
)。
我尝试使用此代码但没有成功,因为loc
我无法使用相对索引:
list = list(
df.loc[
(df["type_name"]=="Match_end")
& (df["second"] == dict.get(df["match_id"]))
]["match_id"].values
)
我需要第二个条件中的一些东西来帮助我根据match_id
每行的值使用字典。
是否有人建议做这件事(有或没有loc
)?
NB
我知道如何在“match_id”上使用 FOR CICLE 来做到这一点,但我正在寻找一种不使用 FOR 循环的方法。
谢谢
解决方案
按列使用Series.map
和比较:second
d = { 101 : 2500,102 : 2700, 103 : 2000}
print (df['match_id'].map(d))
0 2500
1 2500
2 2500
3 2700
4 2700
5 2000
Name: match_id, dtype: int64
L = df.loc[df['match_id'].map(d).eq(df['second']) &
(df["type_name"]=="Match_end"), 'match_id'].tolist()
print (L)
[101, 103]
推荐阅读
- sql - 在一个结果行中选择具有给定时间间隔的 id 历史记录的行
- background-process - python 2.7.5:在后台运行整个函数
- eloquent - 我可以强制 Eloquent 模型 created_at 使用 unix_timestamp() 作为 DB 服务器时间来对抗时间漂移
- ruby-on-rails - Ruby on Rails - ActionCable - : undefined method `redis_connection_for_subscriptions' for #
我最近开始使用 ActionCable 并设法让多个频道正常工作,但是在测试频道时我遇到了问题。
示例频道 - 订阅方法:
- variable-assignment - 匈牙利方法 - 3 选择分配
- python - 使用 dask 监控 xarrays 拆分应用组合的进度
- c# - 如何通过 C# 客户端在 Azure DevOps 中创建代理池?
- python - C++中的SDK需要在python中调用这些函数
- sql-server - 具有自定义值的数据透视表
- vb.net - 获取 PC 用户名/磁盘并使用它来删除文件/文件夹