为什么我会得到这个错误 "ValueError: cannot reindex from a duplicate axis"?

7 浏览
0 Comments

为什么我会得到这个错误 "ValueError: cannot reindex from a duplicate axis"?

这里我只展示了代码中出错的部分。在这里,我将两个不同的数据框连接在一起,这两个数据框分别添加到了两个不同的列表中。\n

path1 = '/home/Desktop/computed_2d_blaze/'
path2 = '/home/Desktop/computed_1d/'
path3 = '/home/Desktop/sn_airmass_seeing/'
dir1 = [x for x in os.listdir(path1) if '.ares' in x]
dir2 = [x for x in os.listdir(path2) if '.ares' in x]
dir3 = [x for x in os.listdir(path3) if '.ares' in x]
lst = []
lst1 = []
for file1, file2,file3 in zip(dir1,dir2,dir3):
   df1 = pd.read_table(path1+file1, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')
   df2 = pd.read_table(path2+file2, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')
   df1 = df1.groupby('wave').mean().reset_index()
   df1 = df1.sort_values('wave').reset_index(drop=True)
   df2 = df2.sort_values('wave').reset_index(drop=True)
   dfs = pd.merge(df1,df2, on='wave', how='inner')
   dfs['delta_ew'] = (dfs.EWs_x - dfs.EWs_y)
   dfs=dfs.filter(items=['wave','delta_ew'])
   lst.append(dfs)
   df3 = pd.read_table(path3+file3, skiprows=0, usecols=(0,1,2),names=['seeing','airmass','snr'],delimiter=r'\s+')
   lst1.append(df3)
[df.set_index('wave', inplace=True) for df in lst]
df=pd.concat(lst,axis=1,join='inner')
x = pd.concat(lst1,axis=1,join='inner')
for z in df.index:
   t = x.loc[0, 'airmass']
   s = df.loc[z, 'delta_ew']
   dfs = pd.concat([s,t],axis=1,names=['delta_ew','airmass'])
   dfs = dfs[np.abs(dfs.delta_ew - dfs.delta_ews.mean()) <= (dfs.delta_ews.mad())]

\n我试图创建一个新的数据框,因为delta_ew中有一些异常值,所以为了去除它们,我这样做。但是当我尝试这样做时,我得到了这个错误:ValueError: cannot reindex from a duplicate axis。\n我不明白如何解决这个错误。有人能告诉我我在哪里犯了错吗?\n以下是完整的回溯信息\n

 Traceback (most recent call last):
  File "/home/gyanender/Desktop/r_values/airmass_vs_ew/delta_ew/for_rvalues.py", line 72, in 
    dfs = pd.concat([s,t],axis=1,names=['delta_ew','airmass'])
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/reshape/concat.py", line 213, in concat
    return op.get_result()
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/reshape/concat.py", line 385, in get_result
    df = cons(data, index=index)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 330, in __init__
    mgr = self._init_dict(data, index, columns, dtype=dtype)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 461, in _init_dict
    return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 6168, in _arrays_to_mgr
    arrays = _homogenize(arrays, index, dtype)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 6465, in _homogenize
    v = v.reindex(index, copy=False)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/series.py", line 2681, in reindex
    return super(Series, self).reindex(index=index, **kwargs)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/generic.py", line 3023, in reindex
    fill_value, copy).__finalize__(self)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/generic.py", line 3041, in _reindex_axes
    copy=copy, allow_dups=False)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/generic.py", line 3145, in _reindex_with_indexers
    copy=copy)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/internals.py", line 4139, in reindex_indexer
    self.axes[axis]._can_reindex(indexer)
  File "/home/gyanender/.local/lib/python2.7/site-packages/pandas/core/indexes/base.py", line 2944, in _can_reindex
    raise ValueError("cannot reindex from a duplicate axis")
ValueError: cannot reindex from a duplicate axis

0
0 Comments

为什么会出现这个错误"ValueError: cannot reindex from a duplicate axis?"

这个错误通常在索引存在重复值时,当你将一个列与另一个列连接或赋值时会出现。

错误出现在代码`dfs = pd.concat([s,t],axis=1,names=['delta_ew','airmass'])`这一行。我相信我找到了解决这个问题的方法。只需要在`concat`代码中添加`ignore_index=True`。

像这样:

dfs = pd.concat([s,t],axis=1,names=['delta_ew','airmass'], ignore_index=True )

这将重新创建索引。

注意:这里的`index`指的是行和列的名称。

而不是使用`loc`,尝试使用`ix`,例如:`t = x.ix[0, 'airmass']`和`s = df.ix[z, 'delta_ew']`

嘿,问题出在这一行`dfs = pd.concat([s,t],axis=1,names=['delta_ew','airmass'])`,如果我不使用`axis=1`,它就可以正确地连接。但是我的问题是我想在`axis=1`上连接它。

我知道这个问题的原因是,当你使用`axis=1`时,它会改变索引,而不仅仅是列名。

先生,点赞不重要!我被卡住了,我必须解决这个问题。

我觉得还有另一种解决方法,但不知道是否有任何函数或类似`q = pd.DataFrame([s,t],ignore_index=True)`的东西可以解决这个问题,但不幸的是,我没有找到任何解决方法。

是的,我尝试过`pd.concat([s.t],ignore_index=True)`,但没有尝试过`pd.DataFrame([s.t],ignore_index=True)`。我想创建一个新的数据框而不是连接这两个序列。但不幸的是,那个也不起作用。

你可以使用`merge`而不是`concat`,参考链接:pandas.pydata.org/pandas-docs/stable/…

当`axis`为0时,请提供您的输出结果。

让我们在聊天中继续讨论

0
0 Comments

这个问题的出现的原因是在使用concat函数合并两个pandas系列时,出现了重复的轴,导致无法重新索引。

解决方法是使用字典来代替concat函数。首先,将pandas系列t和s的值转换为字典,然后将该字典转换为DataFrame。以下是解决方法的代码示例:

for z in df.index:
    t = x.loc[0, 'airmass']
    t = t.values
    s = df.loc[z, 'delta_ew']
    s = s.values
    dic = dict(zip(s,t))      
    q = pd.DataFrame(dic.items(), columns=['ew', 'airmass'])
    q = q[np.abs(q.ew - q.ew.mean()) <= (q.ew.mad())]

通过这种方法,可以成功解决"ValueError: cannot reindex from a duplicate axis"错误。

0