简体   繁体   English

从熊猫数据框中匹配和提取值

[英]Matching and extracting values from pandas dataframe

I'm trying to find matching values in a pandas dataframe. 我正在尝试在熊猫数据框中找到匹配的值。 Once a match is found I want to perform some operations on the row of the dataframe. 找到匹配项后,我要对数据框的行执行一些操作。

Currently I'm using this Code: 目前,我正在使用以下代码:

import pandas as pd

d = {'child_id': [1,2,5,4,7,8,9,10],
 'parent_id': [3,4,1,3,11,6,12,13],
 'content': ["thon","pan","py","das","ten","sor","js","on"]}

df = pd.DataFrame(data=d)

df2 = pd.DataFrame(columns = ("content_child", "content_parent"))

for i in range(len(df)):

        for j in range(len(df)):

            if str(df['child_id'][j]) == str(df['parent_id'][i]):
                content_child = str(df["content"][i])

                content_parent = str(df["content"][j])

                s = pd.Series([content_child, content_parent], index=['content_child', 'content_parent'])
                df2 = df2.append(s, ignore_index=True)
            else:
                pass

 print(df2)

This Returns: 这返回:

  content_child content_parent
0           pan            das
1            py           thon

I tried using df.loc functions, but I only succeed in getting either Content from child or Content from parent: 我尝试使用df.loc函数,但仅成功从子级获取Content或从父级获取Content:

df.loc[df.parent_id.isin(df.child_id),['child_id','content']]

Returns: 返回:

      child_id content
1         2     pan
2         5      py

Is there an fast alternative to the loop I have written? 有没有我写的循环的快速替代方案?

You can use just join data frames with condition if left part child_id is equal to right part parent_id . 您可以使用刚刚join的具有条件的数据帧,如果留下一部分child_id等于右侧部分parent_id

df.set_index('parent_id').join(df.set_index('child_id'), rsuffix='_').dropna()

this code will create two data tables with ids parent_id and child_id . 此代码将创建两个ID为parent_idchild_id数据表。 Then join them as usual SQL join. 然后像往常一样将它们加入SQL连接。 After all drop NaN values and get content column. 毕竟放下NaN值并获取content列。 Which is what you want. 你想要哪一个。 There are 2 content columns. 有2个内容列。 one of them is parent content and second is child content. 其中之一是父内容,第二是子内容。

For improve performance use map : 为了提高性能,请使用map

df['content_parent'] = df['parent_id'].map(df.set_index('child_id')['content'])
df = (df.rename(columns={'content':'content_child'})
        .dropna(subset=['content_parent'])[['content_child','content_parent']])
print (df)
  content_child content_parent
1           pan            das
2            py           thon

Or merge with default inner join: 或与默认内部联接merge

df = (df.rename(columns={'child_id':'id'})
        .merge(df.rename(columns={'parent_id':'id'}), 
              on='id', 
              suffixes=('_parent','_child')))[['content_child','content_parent']]
print (df)
  content_child content_parent
0            py           thon
1           pan            das

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM