簡體   English   中英

重命名列表數據框中元素的最有效方法

[英]Most efficient way to rename elements in dataframe of lists

我有兩個數據框,其中一個包含寵物ID和名稱,另一個用戶和他們喜歡的寵物的ID列表。 我想把它變成一個dict,其中鍵是用戶,值是他們喜歡的所有寵物的名字。

    id  name
0   4   Bert
1   5   Ernie
2   6   Jeff
3   7   Bob
4   8   Puppy
5   9   Socks
6   12  Cyoot
    user_email  likes
0   matt@google.com [4, 5, 6, 7, 8, 9, 12]
1   gabe@google.com [4, 8, 9, 6, 5, 12]

根據我的理解,你可以嘗試:

d= df.set_index('id')['name'].to_dict()
df1.likes=df1.likes.apply(lambda x: [d.get(item,item)  for item in x])
print(df1)

        user_email                                          likes
0  matt@google.com  [Bert, Ernie, Jeff, Bob, Puppy, Socks, Cyoot]
1  gabe@google.com       [Bert, Puppy, Socks, Jeff, Ernie, Cyoot]

對於喜歡電子郵件的字典:

print(df1.set_index('user_email')['likes'].to_dict())

{'matt@google.com': ['Bert', 'Ernie', 'Jeff', 'Bob', 'Puppy', 'Socks', 'Cyoot'],\
  'gabe@google.com': ['Bert', 'Puppy', 'Socks', 'Jeff', 'Ernie', 'Cyoot']}

第一。 將pet id設置為索引:

pets.set_index('id', inplace=True)

比,申請每個'喜歡'列表一個功能,用相應的寵物名稱替換每個'喜歡':

users.likes = users.likes.map(lambda likes: [pets.loc[like]['name'] for like in likes])

最后 - 您所要做的就是將數據幀設置為字典:

users.set_index('user_email').to_dict()['likes']

假設您的第二個數據listlikes列是類型list我們可以執行以下操作:

將列表統一到行

df3 = df2.set_index('user_email').likes.apply(pd.Series).stack().reset_index(level=0).rename(columns={0:'likes'})

print(df3)
        user_email  likes
0  matt@google.com    4.0
1  matt@google.com    5.0
2  matt@google.com    6.0
3  matt@google.com    7.0
4  matt@google.com    8.0
5  matt@google.com    9.0
6  matt@google.com   12.0
0  gabe@google.com    4.0
1  gabe@google.com    8.0
2  gabe@google.com    9.0
3  gabe@google.com    6.0
4  gabe@google.com    5.0
5  gabe@google.com   12.0

將名稱合並到數據框

df4 = df3.merge(df1, left_on='likes', right_on='id').drop(['likes', 'id'],axis=1)

print(df4)
         user_email   name
0   matt@google.com   Bert
1   gabe@google.com   Bert
2   matt@google.com  Ernie
3   gabe@google.com  Ernie
4   matt@google.com   Jeff
5   gabe@google.com   Jeff
6   matt@google.com    Bob
7   matt@google.com  Puppy
8   gabe@google.com  Puppy
9   matt@google.com  Socks
10  gabe@google.com  Socks
11  matt@google.com  Cyoot
12  gabe@google.com  Cyoot

使用groupby將行轉換回列表

df_final = df4.groupby('user_email').agg(list).reset_index()

print(df_final)
        user_email                                           name
0  gabe@google.com       [Bert, Ernie, Jeff, Puppy, Socks, Cyoot]
1  matt@google.com  [Bert, Ernie, Jeff, Bob, Puppy, Socks, Cyoot]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM