【问题标题】:set_index not working as expected on a pandas dataframeset_index 在 pandas 数据帧上没有按预期工作
【发布时间】:2020-11-16 14:40:45
【问题描述】:

在我的代码中,我有一个函数如下,它返回一个简单的数据框:

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) 先声明一行,然后返回它。结果一样?

我真的很困惑为什么我不能将索引设置为函数中代码的一部分?

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    是的,你不能在这里使用inplace 参数。就地返回 None 对象。删除“就地”参数。或者在返回和return multipleConfs 之前执行此行。使用inplace = False(如果未定义则默认),此语句确实返回数据框对象。

    return multipleConfs.set_index('symbol')
    

    multipleConfs.set_index('symbol', inplace = True)
    return multipleConfs
    

    【讨论】:

    • 这正是我认为应该工作的,但不是吗?如果我按照你的建议做,它会返回一个 empty 数据框。如果我没有设置索引(根据我原始帖子中的代码),它会按预期返回数据帧。 ???
    【解决方案2】:

    您必须在参数中指定数据框列:

    multipleConfs.set_index(multipleConfs['symbol'])
    

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 2018-06-02
      • 1970-01-01
      • 2015-03-20
      • 2017-06-29
      • 1970-01-01
      • 2019-06-12
      • 2014-03-27
      • 2020-10-13
      相关资源
      最近更新 更多