替换数据帧列中的值

2024-10-02 22:33:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有数据帧

     site1  site2   site3   site4   site5   site6   site7   site8   site9   site10
session_id                                      
21669   56  55  0   0   0   0   0   0   0   0
54843   56  55  56  55  0   0   0   0   0   0
77292   946 946 951 946 946 945 948 784 949 946
114021  945 948 949 948 945 946 947 945 946 946
146670  947 950 948 947 950 952 946 951 946 947

我有json

^{pr2}$

我试图用

site_dict_upd = {y:x for x,y in site_dict.iteritems()}
full_sites_names = pd.DataFrame()
full_sites_names = [full_sites[col].map(site_dict) for col in sites]

但它返回所有NaN值。 我该怎么解决呢?在


Tags: 数据infornamessitecoldictsites
3条回答

另一种方法是使用applymap

df = df.applymap(lambda x: site_dict_upd[x] if x in site_dict_upd else x)

编辑

或者按照coldspeed的建议:

^{pr2}$

我认为您需要^{},如果不需要替换,请将值转换为相同的types

site_dict_upd = {y:x for x,y in site_dict.items()}
#convert to same types if necessary (int)
df = full_sites_names.astype(int).replace(site_dict_upd)
print (df)
                       site1                        site2             site3  \
session_id                                                                    
21669       www.aldaniti.net                 cc.bingj.com                 0   
54843       www.aldaniti.net                 cc.bingj.com  www.aldaniti.net   
77292                    946                          946               951   
114021                   945                          948               949   
146670                   947  www.decoration-stickers.com               948   

                   site4                        site5  site6  site7  site8  \
session_id                                                                   
21669                  0                            0      0      0      0   
54843       cc.bingj.com                            0      0      0      0   
77292                946                          946    945    948    784   
114021               948                          945    946    947    945   
146670               947  www.decoration-stickers.com    952    946    951   

            site9  site10  
session_id                 
21669           0       0  
54843           0       0  
77292         949     946  
114021        946     946  
146670        946     947  

只需使用.replace方法:

full_sites_names.replace(site_dict_upd, inplace = True)

相关问题 更多 >