Pandas isin在使用con后遇到空DF时返回错误

2024-10-05 10:14:17 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用concat和isin删除所有行时,我遇到:

ValueError: cannot compute isin with a duplicate axis.

同时,如果DF中还有任何行,则不存在问题。另外,不使用concat在任何情况下都是有效的,可以优雅地返回一个空的DF。我正在尝试使用concat,因为在我的用例中它稍微快一点。你知道吗

熊猫0.24.2(最新版本)。你知道吗

df = pd.DataFrame()
for r in range(5):
    df = df.append({'type':'teine', 'id':r}, ignore_index=True)

# Problem line
df = pd.concat([df.reset_index(drop=True), pd.DataFrame({'type':'teine', 'id':5}, index=[0])], sort=True)
dfCopy = df.copy()
df.query("(type == 'teine')", inplace=True)
df = dfCopy[~dfCopy.isin(df).all(axis=1)]

Tags: idtruedataframedfindextypepdvalueerror
2条回答

在队列中:

df = pd.concat([df.reset_index(drop=True), pd.DataFrame({'type':'teine', 'id':5}, index=[0])], sort=True)

无需重置concat(df.reset_index(drop=True))中的索引。但是你必须在concat之后重置索引以避免你的错误。下面是它的样子:

df = pd.concat([df, pd.DataFrame({'type':'teine', 'id':5}, index=[0])], sort=True).reset_index(drop=True)

您只需避免复制索引问题,而不复制它:

df = pd.DataFrame()
for r in range(5):
    df = df.append({'type':'teine', 'id':r}, ignore_index=True)

# Problem line
df = pd.concat([df.reset_index(drop=True), pd.DataFrame({'type':'teine', 'id':5}, index=[max(df.index.values)+1])], sort=True)
dfCopy = df.copy()
df.query("(type == 'teine')", inplace=True)
df = dfCopy[~dfCopy.isin(df).all(axis=1)]

或者,您可以在连接后重置索引:

df = pd.DataFrame()
for r in range(5):
    df = df.append({'type':'teine', 'id':r}, ignore_index=True)

# Problem line
df = pd.concat([df, pd.DataFrame({'type':'teine', 'id':5}, index=[0])], sort=True).reset_index(drop=True)
dfCopy = df.copy()
df.query("(type == 'teine')", inplace=True)
df = dfCopy[~dfCopy.isin(df).all(axis=1)]

相关问题 更多 >

    热门问题