gpt4 book ai didi

Python Pandas key 错误 : 'the label is not in the [index]'

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:54 26 4
gpt4 key购买 nike

我有一个 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: '标签 [179] 不在 [index] 中'。有没有更 Pythonic 的方法来做到这一点?

最佳答案

这是另一种方法。使用 lookup 查找组,并使用 agg 列来列出

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}

关于Python Pandas key 错误 : 'the label is not in the [index]' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46705389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com