当前位置: 首页 > 知识库问答 >
问题:

KeyError:Int64Index([1],dtype='int64')在使用drop_副本时

壤驷涛
2023-03-14

我编写了一个简单的脚本,它应该合并(联合)一些数据帧并删除重复的数据帧。

例如,对于输入:

df_A:
a  1
b  2

df_B:
b  2
c  3

预期产出将是:

df_out:
a  1
b  2
c  3

我编写了以下代码:

def read_dataframes(filenames, basedir):
    return [pd.read_csv(basedir + file, sep='\t', header=None, quoting=csv.QUOTE_NONE) for file in filenames]


def merge_dataframes(dfs, out):
    merged = pd.concat(dfs).drop_duplicates(subset=[0, 1]).reset_index(drop=True)
    merged = merged.iloc[:, [0, 1, 2, 7, 8, 9]]
    merged.to_csv(out, header=None, index=None, sep='\t')

我通过以下方式调用这些函数:

merge_dataframes(read_dataframes(filenames, basedir), output)

我得到一个例外的KeyError

Traceback (most recent call last):
  File "analysis_and_visualization.py", line 70, in <module>
    merge_dataframes(read_dataframes(wild_emb, wild_basedir), 'wild_emb_merged')
  File "analysis_and_visualization.py", line 17, in merge_dataframes
    merged = pd.concat(dfs).drop_duplicates(subset=[0, 1]).reset_index(drop=True)
  File "/Data/user/eliran/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 5112, in drop_duplicates
    duplicated = self.duplicated(subset, keep=keep)
  File "/Data/user/eliran/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 5248, in duplicated
    raise KeyError(diff)
KeyError: Int64Index([1], dtype='int64')

我做错了什么?

共有2个答案

樊胜
2023-03-14

我认为这里的问题不是列1,因为第一列被转换为index,所以一些或所有DataFrames只有一列叫做0

为了防止它使用index_col=False参数在read_csv

def read_dataframes(filenames, basedir):
    return [pd.read_csv(basedir + file, sep='\t', header=None, quoting=csv.QUOTE_NONE, index_col=False) for file in filenames]

另一个问题是,由于某种原因,只有一列数据,因此称为2的第二列不存在。

壤驷经国
2023-03-14

查看框架中的源代码。py和功能重复

看起来数据框中的所有列都不存在。

  # Verify all columns in subset exist in the queried dataframe
        # Otherwise, raise a KeyError, same as if you try to __getitem__ with a
        # key that doesn't exist.
        diff = Index(subset).difference(self.columns)
        if not diff.empty:
            raise KeyError(diff)
df = pd.DataFrame({'col1' : [0,1,2], 'col3' : [1,2,3]})

print(df)

  col1  col3
0     0     1
1     1     2
2     2     3


df.drop_duplicates(subset=['col1','col2'])

   5246         diff = Index(subset).difference(self.columns)
   5247         if not diff.empty:
-> 5248             raise KeyError(diff)
   5249 
   5250         vals = (col.values for name, col in self.items() if name in subset)

KeyError: Index(['col2'], dtype='object')
 类似资料: