簡體   English   中英

熊貓在另一個df中的字符串列表中查找df中一列中的字符串索引

[英]Pandas finding index of string in one column in a df in a list of strings in another df

我有一個看起來像這樣的數據框:

ID 標簽 cnt
123 洛雷姆 34
123 伊普蘇姆 12
456 伊普蘇姆 10
456 多洛爾 2

另一個看起來像這樣的數據框:

ID 標簽
123 ['Ipsum','Lorem']
456 ['洛雷姆','多洛爾']

我需要在 df 2 的標簽列表中找到 df 1 中每個標簽的索引。 所以新的 df 看起來像:

ID 標簽 cnt
123 洛雷姆 34 2
123 伊普蘇姆 12 1
456 伊普蘇姆 10
456 多洛爾 2 2

使用帶有renameDataFrame.explode可能通過GroupBy.cumcount添加Rank列,並通過左連接將其附加到df1

df = df2.explode('tags').rename(columns={'tags':'tag'})
df['Rank'] = df.groupby('id').cumcount().add(1)

df = df1.merge(df, how='left')

print (df)
    id    tag  cnt  Rank
0  123  Lorem   34   2.0
1  123  Ipsum   12   1.0
2  456  Ipsum   10   NaN
3  456  Dolor    2   2.0

df['Rank'] = df['Rank'].astype('Int64')
print (df)
    id    tag  cnt  Rank
0  123  Lorem   34     2
1  123  Ipsum   12     1
2  456  Ipsum   10  <NA>
3  456  Dolor    2     2

您可以通過一個簡單的 lambda 函數來執行此操作,如下所示:

df = df1.merge(df2, on='id')
df['Rank'] = df.apply(lambda x: x.tags.index(x.tag)+1 if x.tag in x.tags else np.nan, axis=1).astype('Int64')

結果數據框將如下所示:

     id   tag  cnt            tags  Rank
0   123 Lorem   34  [Ipsum, Lorem]  2
1   123 Ipsum   12  [Ipsum, Lorem]  1
2   456 Ipsum   10  [Lorem, Dolor]  <NA>
3   456 Dolor   2   [Lorem, Dolor]  2

如果需要,請刪除標簽列:

df.drop(columns = ['tags'])

結果數據框如下所示:

     id   tag  cnt  Rank
0   123 Lorem   34  2
1   123 Ipsum   12  1
2   456 Ipsum   10  <NA>
3   456 Dolor   2   2

暫無
暫無

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

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