如何用单独的dict值替换dataframe列 - python

时间:2018-03-03 16:20:26

标签: python pandas dataframe dictionary-comprehension

我的user_artist_plays数据框显示了一个用户列,但是对于统计计算,我必须将这些混合字符替换为仅int ID。

    users                                       artist  plays
0   00001411dc427966b17297bf4d69e7e193135d89    sting   12763
1   00001411dc427966b17297bf4d69e7e193135d89    stars   8192
2   fffe8c7f952d9b960a56ed4dcb40a415d924b224    cher    117
3   fffe8c7f952d9b960a56ed4dcb40a415d924b224    queen   117

上面只显示了两个用户的多个条目,如果我可以让列匹配单独字典中现有密钥的任何条目,那就没问题了。

users = user_artist_plays['users'].unique()
user_dict = {ni: indi for indi, ni in enumerate(set(users))}
user_dict

{'068156fafd9c4237c174c648d3d484cbf509cb75': 0,
 '6deecfbc46a81e4faf398b2afd991be05ab78f10': 74205,
 '1e23333ff4f637420a8a38d467ccecfda064afb9': 1,
 '0b282cafc949efe4163b7946b7104957a18cf010': 2,
 'd1867cbda35e0d48e9a8390d9f5e079c9d99ea96': 3}

我尝试切换int值:

for k, v in user_dict.items():
        if user_artist_plays['users'].any(k):
            user_artist_plays['users'].replace(v)

它保留了users列的原始值...

1 个答案:

答案 0 :(得分:3)

您似乎需要map

user_artist_plays['users'] = user_artist_plays['users'].map(user_dict)

factorize

user_artist_plays['users'] = pd.factorize(user_artist_plays['users'])[0]