python - 从 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
有没有比我写的循环更快的替代方法?
解决方案
如果 left part等于 right part ,您可以只使用join
带有条件的数据帧。child_id
parent_id
df.set_index('parent_id').join(df.set_index('child_id'), rsuffix='_').dropna()
此代码将创建两个具有 idsparent_id
和child_id
. 然后像往常一样加入它们的 SQL 连接。毕竟删除 NaN 值并获取content
列。这就是你想要的。有 2 个内容栏。其中之一是父内容,第二个是子内容。
推荐阅读
- javascript - 如何生成数字,以便永远没有背靠背的数组索引值?
- selenium - Selenium 脚本中的 JavascriptExecutor 抛出“org.openqa.selenium.JavascriptException: javascript error”
- javascript - 将字符串中的所有字符转换为小于 256 的值的十六进制格式
- bash - 为什么我不能使用 cal 命令在 Git Bash 中显示日历?
- c# - .Net Core T4 Running transformation could not load file or assembly
- html - Flask Fonts not Updating
- virtualbox - qemu - 将虚拟机桥接到 Virtualbox 中的虚拟机
- python - django模型与rest api的关系
- windows - MiKTeX、LaTeX:使用 \newwrite 输出文件和使用 \write 写入时出错——Windows API 错误 2:系统找不到指定的文件
- google-apps-script - 从 Google Geocode API 获取有效住宅地址的零结果