Python:从函数返回DataFrame生成非类型
我有多个命名约定为YYYY.CSV的CSV文件。为了合并CSV,我创建了以下递归函数来将数据帧合并在一起Python:从函数返回DataFrame生成非类型,python,pandas,Python,Pandas,我有多个命名约定为YYYY.CSV的CSV文件。为了合并CSV,我创建了以下递归函数来将数据帧合并在一起 def createFrames(year,parent=None,lim=range(2000,2019)): if year in lim: df=pd.read_csv(str(year)+'.csv') df['Year']=year if parent is None: parent=df else: parent=pd.
def createFrames(year,parent=None,lim=range(2000,2019)):
if year in lim:
df=pd.read_csv(str(year)+'.csv')
df['Year']=year
if parent is None:
parent=df
else:
parent=pd.concat([parent,df])
createFrames(year+1,parent=parent)
else:
print(parent.describe)
return parent
df=createFrames(2000)
df.head()
当我从函数中打印父.descripe时,它会打印完全合并的数据帧。但是,当返回父项时,df变量的类型为NoneType,并且为空。输出如下:
<bound method NDFrame.describe of Unnamed: 0 Player Tm ... ReceivingTD FantasyPoints Year
0 0 Marshall Faulk STL ... 8.0 455.90 2000
1 1 Edgerrin James IND ... 5.0 393.30 2000
2 2 Daunte Culpepper MIN ... 0.0 334.48 2000
3 3 Jeff Garcia SFO ... 0.0 338.52 2000
4 4 Eddie George TEN ... 2.0 334.20 2000
.. ... ... ... ... ... ... ...
617 617 Kaelin Clay NYG ... 0.0 -2.00 2018
618 618 JJ Jones 2TM ... 0.0 -0.70 2018
619 619 Kyle Lauletta NYG ... 0.0 -2.20 2018
620 620 Riley McCarron NWE ... 0.0 -2.00 2018
621 621 Jojo Natson LAR ... 0.0 -2.00 2018
[11280 rows x 29 columns]>
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-119-9ea047491d15> in <module>()
14
15 df=createFrames(2000)
---> 16 df.head()
AttributeError: 'NoneType' object has no attribute 'head'
---------------------------------------------------------------------------
AttributeError回溯(最近一次呼叫上次)
在()
14
15 df=创建帧(2000)
--->16.首长()
AttributeError:“非类型”对象没有属性“头”
如何从函数返回合并后的数据帧?您可能忘记将
return
放在createFrames(year+1,parent=parent)
中。Andrej,函数是递归的,返回语句位于parent.descripe下面,这是执行的。执行递归时,必须从所有分支返回(此处为if..else…
)。否则,在末尾返回None
。