【问题标题】:Pandas Concat: cannot reindex from a duplicate axisPandas Concat:无法从重复的轴重新索引
【发布时间】:2017-08-26 00:58:34
【问题描述】:

我正在尝试concat 一些timeseries。对于某些数据集,这是可行的。我的timeseries 使用date 作为索引。现在对于ts.size 相同的一些数据集,pd.concat 可以完美运行。但是当sizetimeseries 不同时,我得到错误:cannot reindex from a duplicate axis。所以我认为这是由于size 的差异而发生的。如果是这样,我应该用零填充timeseries 吗?

ts.head():

date
2017-03-09    24.6245
2017-03-10    24.5765
2017-03-13    24.5767
2017-03-14    24.5344
2017-03-15    24.5440

我已经坚持了一天,因此感谢您提供任何帮助。谢谢 这是我发布的原始问题,您可以查看我的代码:ValueError: cannot reindex from a duplicate axis Pandas。我只是想知道这是否有问题。

我的代码:

def get_adj_nav(self, fund_id):
    df_nav = read_frame(
        super(__class__, self).filter(fund__id=fund_id, nav__gt=0).exclude(fund__account_class=0).order_by(
            'valuation_period_end_date'), coerce_float=True,
        fieldnames=['income_payable', 'valuation_period_end_date', 'nav', 'outstanding_shares_par'],
        index_col='valuation_period_end_date')
    df_dvd, skip = self.get_dvd(fund_id=fund_id)
    df_nav_adj = calculate_adjusted_prices(
        df_nav.join(df_dvd).fillna(0).rename_axis({'payout_per_share': 'dividend'}, axis=1), column='nav')
return df_nav_adj

def json_total_return_table(request, fund_account_id):
ts_list = []
for fund_id in Fund.objects.get_fund_series(fund_account_id=fund_account_id):
    if NAV.objects.filter(fund__id=fund_id, income_payable__lt=0).exists():
        ts = NAV.objects.get_adj_nav(fund_id)['adj_nav']
        ts.name = Fund.objects.get(id=fund_id).account_class_description
        ts_list.append(ts.copy())
        print(ts)
    df_adj_nav = pd.concat(ts_list, axis=1) # ====> Throws error
    cols_to_datetime(df_adj_nav, 'index')
    df_adj_nav = ffn.core.calc_stats(df_adj_nav.dropna()).to_csv(sep=',')

【问题讨论】:

  • 你能粘贴一些你的代码吗?
  • @cᴏʟᴅsᴘᴇᴇᴅ 没问题
  • @anderish 我想你回答了你自己的问题。由于您沿轴 = 1 连接(添加更多列),因此您需要保持“列”长度相同。如果该标准不存在,则 concat 功能将不知道如何填写缺失的数据。您可能要考虑的另一种模式是 merge() link

标签: python pandas


【解决方案1】:

所以我认为我说它失败的原因是由于尺寸不同是正确的。所以我改用merge。 我只是更改了这一行:df_adj_nav = pd.concat(ts_list, axis=1)

到这一行:df_adj_nav = reduce(lambda x, y: pd.merge(x, y, left_index=True, right_index=True, how='outer'), ts_list)

感谢@HodgePodge 的提示:)

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 2018-02-02
    • 2019-08-07
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    相关资源
    最近更新 更多