【问题标题】:ValueError: cannot reindex from a duplicate axis using isin with pandasValueError:无法使用 isin 和 pandas 从重复的轴重新索引
【发布时间】:2015-06-11 17:55:15
【问题描述】:

我正在尝试将邮政编码缩短为各种文件,但我不断收到

ValueError: 无法从重复的轴重新索引

我已经阅读了有关 Stackoverflow 的其他文档,但我还没有打算弄清楚它为什么会重复轴。

import csv
import pandas as pd
from pandas import DataFrame as df
fp = '/Users/User/Development/zipcodes/file.csv'
file1 = open(fp, 'rb').read()
df = pd.read_csv(fp, sep=',')

df = df[['VIN', 'Reg Name', 'Reg Address', 'Reg City', 'Reg ST', 'ZIP',
         'ZIP', 'Catagory', 'Phone', 'First Name', 'Last Name', 'Reg NFS',
         'MGVW', 'Make', 'Veh Model','E Mfr', 'Engine Model', 'CY2010',
         'CY2011', 'CY2012', 'CY2013', 'CY2014', 'CY2015', 'Std Cnt', 
        ]]
#reader.head(1)
df.head(1)
zipBlue = [65355, 65350, 65345, 65326, 65335, 64788, 64780, 64777, 64743,
64742, 64739, 64735, 64723, 64722, 64720]

还包含zipGreen, zipRed, zipYellow, ipLightBlue 但未包括在示例中。

def IsInSort():
    blue = df[df.ZIP.isin(zipBlue)]
    green = df[df.ZIP.isin(zipGreen)]
    red = df[df.ZIP.isin(zipRed)]
    yellow = df[df.ZIP.isin(zipYellow)]
    LightBlue = df[df.ZIP.isin(zipLightBlue)]
def SaveSortedZips():
    blue.to_csv('sortedBlue.csv')
    green.to_csv('sortedGreen.csv')
    red.to_csv('sortedRed.csv')
    yellow.to_csv('sortedYellow.csv')
    LightBlue.to_csv('SortedLightBlue.csv')
IsInSort()
SaveSortedZips()

1864 # 尝试在具有重复 1865 的轴上重新索引
如果不是 self.is_unique 和 len(indexer): -> 1866 raise ValueError("cannot reindex from a duplicate axis") 1867 1868 def reindex(self, target, method=None, 级别=无,限制=无):

ValueError: 无法从重复的轴重新索引

【问题讨论】:

  • 您在哪一行得到错误?您的示例与以下内容有何不同: df = pd.DataFrame({'A':[1,1,2,4]},index=[1,1,2,2]); df[df.A.isin([1,2])]
  • () 中的 ValueError Traceback (最近一次调用最后一次) 11 Yellow.to_csv('sortedYellow.csv') 12 LightBlue.to_csv( 'SortedLightBlue.csv') ---> 13 IsInSort() 14 SaveSortedZips()
  • 不确定这是什么:from pandas import DataFrame as df 但不是一个好主意。按照惯例,df 是pandas.DataFrame 的一个实例。您应该删除该行。如果您想将 DataFrame 带入命名空间而不必在其前面加上 pd,您可以,但忽略 as df
  • 谢谢约翰。我做出了改变。
  • 不确定发生了什么,但没有数据很难弄清楚。如果您可以使用小样本数据集重现错误,那将有所帮助。

标签: python pandas dataframe


【解决方案1】:

我很确定你的问题与你的面具有关

df = df[['VIN', 'Reg Name', 'Reg Address', 'Reg City', 'Reg ST', 'ZIP',
         'ZIP', 'Catagory', 'Phone', 'First Name', 'Last Name', 'Reg NFS',
         'MGVW', 'Make', 'Veh Model','E Mfr', 'Engine Model', 'CY2010',
         'CY2011', 'CY2012', 'CY2013', 'CY2014', 'CY2015', 'Std Cnt', 
        ]]

'ZIP' 在那里两次。删除其中一个应该可以解决问题。

ValueError: cannot reindex from a duplicate axis 错误是这些非常非常神秘的 pandas 错误之一,它根本不会告诉您错误是什么。

该错误通常与在操作之前或之后(内部)命名相同的两列有关。

【讨论】:

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