Skip to main content
 首页 » 编程设计

python之pandas 中用于根据 df 上的应用函数的输出创建数据帧的正确习惯用法是什么

2025年05月04日12lvdongjie

编辑 --- 我取得了一些进展,发现了 pandas 中的 drop_duplicates 方法,它保存了我创建的一些自定义去重函数。 这在几个方面改变了问题,b/c 它改变了我的初始要求。

我需要执行的操作之一是获取最新的提要条目 --- 提要 URL 存在于数据框中的一列中。完成应用后,我会返回反馈对象:

import pandas as pd 
import feedparser 
import datetime 
 
df_check_feeds = pd.DataFrame({'account_name':['NYTimes', 'WashPo'],'feed_url':['http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml', 'http://feeds.washingtonpost.com/rss/homepage'], 'last_update':['2015-12-28 23:50:40', '2015-12-28 23:50:40']}) 
df_check_feeds["feeds_results"] = pd.DataFrame(df_check_feeds.feed_url.apply(lambda feed_url: feedparser.parse(feed_url))) 
df_check_feeds["entries"] = df_check_feeds.feeds_results.apply(lambda x: x.entries) 

所以,现在我被“条目”列中的提要条目困住了,我想在一个应用方法中创建两个新的数据帧,并立即连接这两个帧。

我已经在 for 循环中表达了等价物:

frames_list = [] 
for index in df_check_feeds.index: 
     df_temp = pd.DataFrame(df_check_feeds.entries[index]) 
     df_temp['account_name'] = df_check_feeds.ix[index,'account_name'] 
     # some error checking on the info here 
     frames_list.append(df_temp) 
df_total_results = pd.concat(frames_list) 
df_total_results 

我意识到我可以在 for 循环中执行此操作(并且确实已经写过),但我觉得有一些更好、更简洁的 pandas 惯用方式来编写此语句。

请您参考如下方法:

更紧凑的方式可能是:

df_total_results = df_check_feeds.groupby('account_name').apply(lambda x: pd.DataFrame(x['entries'].iloc[0]))