Python 如何基于其他行和其他数据帧查找数据帧中的行

Python 如何基于其他行和其他数据帧查找数据帧中的行,python,pandas,python-3.7,Python,Pandas,Python 3.7,从我提出的问题中,我得到了一个类似于以下内容的JSON响应: (请注意:id在我下面的示例数据中是数字字符串,但有些是字母数字) 数据=↓** { "state": "active", "team_size": 20, "teams": { "id": "12345679", "name": "Good Guys", "level": 10, "attacks": 4, "destruction_percentage": 22.6, "

从我提出的问题中,我得到了一个类似于以下内容的JSON响应:

(请注意:
id
在我下面的示例数据中是数字字符串,但有些是字母数字)

数据=↓**

{
  "state": "active",
  "team_size": 20,
  "teams": {
    "id": "12345679",
    "name": "Good Guys",
    "level": 10,
    "attacks": 4,
    "destruction_percentage": 22.6,
    "members": [
      {
        "id": "1",
        "name": "John",
        "level": 12
      },
      {
        "id": "2",
        "name": "Tom",
        "level": 11,
        "attacks": [
          {
            "attackerTag": "2",
            "defenderTag": "4",
            "damage": 64,
            "order": 7
          }
        ]
      }
    ]
  },
  "opponent": {
    "id": "987654321",
    "name": "Bad Guys",
    "level": 17,
    "attacks": 5,
    "damage": 20.95,
    "members": [
      {
        "id": "3",
        "name": "Betty",
        "level": 17,
        "attacks": [
          {
            "attacker_id": "3",
            "defender_id": "1",
            "damage": 70,
            "order": 1
          },
          {
            "attacker_id": "3",
            "defender_id": "7",
            "damage": 100,
            "order": 11
          }
        ],
        "opponentAttacks": 0,
        "some_useless_data": "Want to ignore, this doesn't show in every record"
      },
      {
        "id": "4",
        "name": "Fred",
        "level": 9,
        "attacks": [
          {
            "attacker_id": "4",
            "defender_id": "9",
            "damage": 70,
            "order": 4
          }
        ],
        "opponentAttacks": 0
      }
    ]
  }
}
我使用以下方式加载此文件:

df = json_normalize([data['team'], data['opponent']],
                     'members',
                     ['id', 'name'],
                     meta_prefix='team.',
                     errors='ignore')
print(df.iloc(1))
attacks              [{'damage': 70, 'order': 4, 'defender_id': '9'...
id                                                                   4
level                                                                9
name                                                              Fred
opponentAttacks                                                      0
some_useless_data                                                  NaN
team.name                                                     Bad Guys
team.id                                                      987654321
Name: 3, dtype: object
我有一个由三部分组成的问题

  • 如何使用member标记获得与上面类似的行?我试过:

    member = df[df['id']=="1"].iloc[0]
    #Now this works, but am I correctly doing this?
    #It just feels weird is all.
    
  • 如果只记录攻击而不记录防御(即使提供了defender_id),我如何检索成员的防御?我试过:

    df.where(df['tag']==df['attacks'].str.get('defender_id'), df['attacks'], axis=0)
    #This is totally not working.. Where am I going wrong?
    
  • 由于我正在从API检索新数据,因此需要检查数据库中的旧数据,以查看是否存在任何新的攻击。然后我可以循环新的攻击,然后向用户显示攻击信息

    这我真的搞不懂,我已经试着研究过了,而且我觉得离我需要的任何地方都很近了,但是我仍然很难把我的大脑围绕在这个概念上。基本上,我的逻辑如下:


  • 我知道除了我提供的文档(基本上是为了显示我想要的输入/输出),上面的函数几乎没有显示任何效果,但相信我,我一直在为这部分绞尽脑汁。我一直在研究
    merg
    ing所有攻击,然后执行
    reset_index()
    ,这只会引发一个错误,因为攻击是一个列表。我在上面链接的第二个问题中的
    map()
    函数把我难住了

    按顺序提及您的问题(代码如下):

  • 我看起来像是
    id
    是数据的唯一索引,因此您可以使用
    df.set_index('id')
    ,例如,它允许您通过
    df.loc['1']
    按玩家id访问数据
  • 据我了解,您的数据中,每个
    攻击
    中列出的所有词典都是独立的,因此不需要相应的玩家id(因为
    攻击者id
    防御者id
    似乎足以识别数据)。因此,我建议不要处理包含列表的行,而是将这些数据交换到它自己的数据框中,这样可以方便地访问这些数据
  • 一旦您将
    攻击
    存储在自己的数据框中,您就可以简单地比较索引以过滤掉旧数据
  • 下面是一些示例代码来说明各个要点:

    # Question 1.
    df.set_index('id', inplace=True)
    print(df.loc['1'])  # For example player id 1.
    
    # Question 2 & 3.
    attacks = pd.concat(map(
        lambda x: pd.DataFrame.from_dict(x).set_index('order'),  # Is 'order' the right index?
        df['attacks'].dropna()
    ))
    
    # Question 2.
    print(attacks[attacks['defender_id'] == '1'])  # For example defender_id 1.
    
    # Question 3.
    old_attacks = attacks.iloc[:2]  # For example.
    new_attacks = attacks[~attacks.index.isin(old_attacks.index)]
    print(new_attacks)
    

    已经一个小时了,我为刚刚编辑的模糊标题道歉。我不知道那里发生了什么。df1是什么?是不是
    df.iloc[1]
    ?应该是
    df
    。我的缺点是,我一直在做很多关于如何使用熊猫的研究。我找到了我的答案,@a_guest回答正确。是的,我也准备这么说:-)谢谢,我知道这些都是新手问题。我刚开始使用熊猫,很难理解它的细微差别。在过去的一天里做了很多研究,一直在看视频。谢谢你的回答!
    # Question 1.
    df.set_index('id', inplace=True)
    print(df.loc['1'])  # For example player id 1.
    
    # Question 2 & 3.
    attacks = pd.concat(map(
        lambda x: pd.DataFrame.from_dict(x).set_index('order'),  # Is 'order' the right index?
        df['attacks'].dropna()
    ))
    
    # Question 2.
    print(attacks[attacks['defender_id'] == '1'])  # For example defender_id 1.
    
    # Question 3.
    old_attacks = attacks.iloc[:2]  # For example.
    new_attacks = attacks[~attacks.index.isin(old_attacks.index)]
    print(new_attacks)