首页 > 解决方案 > 从 pandas 数据框中匹配和提取值

问题描述

我正在尝试在熊猫数据框中找到匹配的值。一旦找到匹配项,我想对数据框的行执行一些操作。

目前我正在使用此代码:

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)

这返回:

  content_child content_parent
0           pan            das
1            py           thon

我尝试使用 df.loc 函数,但我只能成功地从子项或父项获取内容:

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

回报:

      child_id content
1         2     pan
2         5      py

有没有比我写的循环更快的替代方法?

标签: pythonpandas

解决方案


如果 left part等于 right part ,您可以只使用join带有条件的数据帧。child_idparent_id

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

此代码将创建两个具有 idsparent_idchild_id. 然后像往常一样加入它们的 SQL 连接。毕竟删除 NaN 值并获取content列。这就是你想要的。有 2 个内容栏。其中之一是父内容,第二个是子内容。


推荐阅读