从 pandas 数据框中匹配和提取值 [英] 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)
这将返回:
content_child content_parent
0 pan das
1 py thon
我尝试使用df.loc函数,但仅成功从子级获取内容或从父级获取内容
I tried using df.loc functions, but I only succeed in getting either Content from child or Content from parent:
df.loc[df.parent_id.isin(df.child_id),['child_id','content']]
返回:
child_id content
1 2 pan
2 5 py
除了我编写的循环以外,还有其他快速的选择吗?
Is there an fast alternative to the loop I have written?
推荐答案
如果左侧部分child_id
等于右侧部分parent_id
,则可以仅使用join
数据帧作为条件.
You can use just join
data frames with condition if left part child_id
is equal to right part parent_id
.
df.set_index('parent_id').join(df.set_index('child_id'), rsuffix='_').dropna()
此代码将创建两个ID为parent_id
和child_id
的数据表.然后像往常一样将它们加入SQL连接.毕竟,删除NaN值并获得content
列.您要哪一个.有2个内容列.其中之一是父内容,第二是子内容.
this code will create two data tables with ids parent_id
and child_id
. Then join them as usual SQL join. After all drop NaN values and get content
column. Which is what you want. There are 2 content columns. one of them is parent content and second is child content.
这篇关于从 pandas 数据框中匹配和提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!