Python Pandas KeyError:'标签不在[index]中

时间:2017-10-12 08:57:14

标签: python list pandas dataframe

我有一个duplicates_to_fetch索引数据框:

            mail_domaine         Values
0                 @A.com         [0, 2]
1                 @B.com         [1, 4]

以下df_to_rearrange数据框

        movie_name              df_pname 
0                A                [mr a]   
1                B                [mr b]   
2               Aa               [mr aa]   
3                D                [mr d]   
4               Bb       [mr Bb, mr Bbb]
5                E                [mr e]

我想拥有以下转换后的数据框

        movie_name                    df_pname 
0          [A, Aa]               [mr a, mr aa]   
1          [B, Bb]       [mr b, mr Bb, mr Bbb]   
3              [D]                      [mr d] 
5              [E]                      [mr e]    

然而......当我删除行时,算法因缺少索引而停止

我确实喜欢

for i in range(0,len(druplicates_to_fetch)):
      mylist = duplicates_to_fetch.loc[i,"Values"]
      index_to_fetch_on = mylist[0]

      # rearrange mylist (which can have >2 values)
      mylist = [myindex for myindex in mylist if myindex != index_to_fetch_on]

      for j in mylist:
            df_to_rearrange.loc[index_to_fetch, "df_pname"].append(df_to_rearrange.loc[j, "df_pname"])
            df_to_rearrange.drop(df_to_rearrange.index[j], inplace=True)

错误是以下KeyError: 'the label [179] is not in the [index]'。我有更多的Pythonic方法吗?

3 个答案:

答案 0 :(得分:1)

这是另一种方法。将lookup用于群组,将agg列添加到list

In [78]: lookup = {v: i for i, x in enumerate(duplicates_to_fetch['Values']) for v in x}

In [79]: (df_to_rearrange.groupby(df_to_rearrange.index.to_series().map(lookup).fillna(''))
             .agg({'movie_name': lambda x: [v for v in x], 
                   'df_pname': lambda x: [a for v in x.values for a in v]})
             .reset_index(drop=True))
Out[79]:
  movie_name               df_pname
0    [A, Aa]          [mr a, mr aa]
1    [B, Bb]  [mr b, mr Bb, mr Bbb]
2        [D]                 [mr d]

详细

In [959]: duplicates_to_fetch
Out[959]:
  mail_domaine  Values
0       @A.com  [0, 2]
1       @B.com  [1, 4]

In [960]: df_to_rearrange
Out[960]:
  movie_name         df_pname
0          A           [mr a]
1          B           [mr b]
2         Aa          [mr aa]
3          D           [mr d]
4         Bb  [mr Bb, mr Bbb]
In [958]: lookup
Out[958]: {0: 0, 1: 1, 2: 0, 4: 1}

答案 1 :(得分:0)

一个解决方案是

df_to_rearrange.drop(df_to_rearrange.index[np.where((df_to_rearrange.index==j))], inplace=True)

答案 2 :(得分:0)

.reindex()作为.loc的替代方案

http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-deprecate-loc-reindex-listlike

df_to_rearrange.reindex([index_to_fetch], ["df_pname"]).append(df_to_rearrange.reindex([j], ["df_pname"]))