在我的代码中,我有一个函数如下所示,它返回一个简单的dataframe:
def find_highest_confs(dictOfCurves):
"""
Parameters
----------
dictOfCurves : Function takes in a dictionary containing stocks(key) and a
dataframe per stock containing stocktrend data for that stock
Returns
-------
multipleConfs : A dataframe with per row the stock (ticker symbol), start
date of the highest order trend, the nr of times that trend was confirmed
and the date of last confirmation
"""
multipleConfs = pd.DataFrame(columns = ['symbol', 'max confirmations', \
'Launch date', 'Last confirmation'])
for item in dictOfCurves:
df = dictOfCurves[item]
try:
df.sort_values(by = ['confirmations'], ascending = False, inplace = True)
maxLaunchDate = df[df['confirmations'] == df['confirmations'].max()].index[0]
lastConf = df.loc[maxLaunchDate, 'Last confirmation']
newData = {'symbol': item, 'max confirmations': df['confirmations'].max(), \
'Launch date': maxLaunchDate, 'Last confirmation': lastConf}
except:
newData = {'symbol': item, 'max confirmations': np.nan, 'Launch date': np.nan, \
'Last confirmation': np.nan}
multipleConfs = multipleConfs.append(newData, ignore_index = True)
return multipleConfs现在,这段代码运行良好,并返回一个df,如下所示:
highest = find_highest_confs(curves)它会像预期的那样生成数据,没有索引集。
如果我然后设置了这样的索引:
highest.set_index('symbol', inplace = True)同样,的工作方式与预期的一样。
奇怪的是..。
如果我将函数的最后一行更改为:
return multipleConfs.set_index('symbol', inplace = True)它返回一个空NoneType
我还尝试在前面的一行中添加multipleConfs.set_index('symbol', inplace = True)语句,然后返回它。同样的结果?
我真的很困惑为什么不能将索引设置为函数中的代码的一部分?
发布于 2020-11-16 14:47:40
是的,这里不能使用inplace参数。Inplace不返回任何对象。删除“inplace”参数。或者在返回和return multipleConfs之前执行这一行。对于inplace = False (默认情况下未定义),此语句确实返回dataframe对象。
return multipleConfs.set_index('symbol')或
multipleConfs.set_index('symbol', inplace = True)
return multipleConfs发布于 2022-02-26 17:40:52
您必须在参数中指定dataframe列:
multipleConfs.set_index(multipleConfs['symbol'])https://stackoverflow.com/questions/64860042
复制相似问题