Skip to main content
 首页 » 编程设计

python之apply() 返回一个 DataFrame 而不是 Series

2025年02月15日23webabcd

In the folwwing code: 
import pandas as pd 
import sqlite3 
import math 
import numpy 
con = sqlite3.connect(r'C:\Python34\factbook.db') 
facts = pd.read_sql_query('select * from facts;', con) 
facts.dropna(inplace=True) 
facts = facts[facts['area_land']!=0][:] 
facts = facts[facts['population']!=0][:] 
facts.reset_index(drop=True, inplace=True) 
def pop_50(name): 
    pop = facts[facts['name'] == name]['population'] 
    perc = facts[facts['name'] == name]['population_growth'] 
    new_pop = pop*(math.e**(35*perc)) 
    return new_pop 
 
 
x=pd.Series(data=facts['name']) 
z = x.apply(pop_50)  

x 是一个系列:

0                                        Afghanistan 
1                                            Albania 
2                                            Algeria 
3                                            Andorra 
4                                             Angola 
5                                Antigua and Barbuda 
6                                          Argentina 
7                                            Armenia 

等等……

但是 z 不是。这是查看它是什么(DataFrame)的链接: https://www.scribd.com/document/357697929/Doc1

我不明白为什么。 pop_50 func 返回一个结果(我测试过),那么为什么 zed 是一个 DataFrame? pop_50 如何返回一个系列?它需要一行(其中 facts['name']==name)并从中获取一个值(在 population 列下),然后将其称为 pop。它比对 perc 做同样的想法。 new_pop 是 2 个单值的数学组合,因此它也是一个值,而 func 只返回那个值,不是吗?

谢谢。

请您参考如下方法:

pop_50 返回一个 pd.Series。 x.apply(pop_50) 为 x 的每一行调用函数 pop_50 并将该行的值传递给 pop_50 作为参数 name。因此,对于 x 中的第一行,您返回一个系列。又是第二行。你最终得到了一系列的系列......这是一个数据框。此外,x 的索引将是您结果的列。

试试这个:

facts2 = facts.set_index('name') 
 
def pop_50(name): 
 
    pop = facts2.at[name, 'population'] 
    perc = facts2.at[name, 'population_growth'] 
    new_pop = pop*(math.e**(35*perc)) 
    return new_pop 

你也可以使用pd.Series.squeeze

def pop_50(name): 
    pop = facts[facts['name'] == name]['population'].squeeze() 
    perc = facts[facts['name'] == name]['population_growth'].squeeze() 
    new_pop = pop*(math.e**(35*perc)) 
    return new_pop 

如果出于某种原因您无法更改 pop_50,请将其包装在 lambda 中

z = x.apply(lambda name: pop_50(name).squeeze())