从列表字典更新我的数据框
Update my dataframe from a dictionary of list
我有一个带有特定 ID 的数据框,我还有一个列表字典。如果它存在于字典中,我需要从数据框的 ID 更新该 ID,但在字典中它由两个 ID 更新,以下是示例:
数据框
ID
Name
Last Name
1
Peter
Smith
2
John
Allen
7
Rene
Watson
8
Dilan
Foster
词典
Dict = {1: [3, 4], 2: [5, 6], 7: [11], 8:[8]}
预期输出:
ID
Name
Last Name
3
Peter
Smith
4
Peter
Smith
5
John
Allen
6
John
Allen
11
Rene
Watson
8
Dilan
Foster
提前致谢!
让我们试试map
和explode
df.assign(ID=df['ID'].map(dct)).explode('ID', ignore_index=True)
ID Name Last Name
0 3 Peter Smith
1 4 Peter Smith
2 5 John Allen
3 6 John Allen
我有一个带有特定 ID 的数据框,我还有一个列表字典。如果它存在于字典中,我需要从数据框的 ID 更新该 ID,但在字典中它由两个 ID 更新,以下是示例: 数据框
ID | Name | Last Name |
---|---|---|
1 | Peter | Smith |
2 | John | Allen |
7 | Rene | Watson |
8 | Dilan | Foster |
词典
Dict = {1: [3, 4], 2: [5, 6], 7: [11], 8:[8]}
预期输出:
ID | Name | Last Name |
---|---|---|
3 | Peter | Smith |
4 | Peter | Smith |
5 | John | Allen |
6 | John | Allen |
11 | Rene | Watson |
8 | Dilan | Foster |
提前致谢!
让我们试试map
和explode
df.assign(ID=df['ID'].map(dct)).explode('ID', ignore_index=True)
ID Name Last Name
0 3 Peter Smith
1 4 Peter Smith
2 5 John Allen
3 6 John Allen