【问题标题】:Pandas - change string to a numberPandas - 将字符串更改为数字
【发布时间】:2016-06-12 20:41:31
【问题描述】:

我有一个包含大量电子邮件的数据集,我想更改它:

df = pd.DataFrame( [('aatest@gmail.com', 0, 3.0), ('aatest@gmail.com', 1, 2.0), 
                    ('aatest@gmail.com', 1 ,3.0), ('bbtest@gmail.com', 1, 1.0), 
                    ('cctest@gmail.com', 2, 5.0)]) 

df
0  aatest@gmail.com  0  3
1  aatest@gmail.com  1  2
2  aatest@gmail.com  1  3
3  bbtest@gmail.com  1  1
4  cctest@gmail.com  2  5

到这里:

df2 = pd.DataFrame(
[(0, 0, 3.0), (0, 1, 2.0), (0,1 ,3.0), (1, 1, 1.0), (2, 2, 5.0)])

df2
   0  1  2
0  0  0  3
1  0  1  2
2  0  1  3
3  1  1  1
4  2  2  5

即,将电子邮件更改为数字,但相同的电子邮件保持相同的数字

我该怎么做?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用factorize:

    df[0] = pd.factorize(df[0])[0]
    
    print df
    
       0  1  2
    0  0  0  3
    1  0  1  2
    2  0  1  3
    3  1  1  1
    4  2  2  5
    

    rank:

    df[0] = df[0].rank(method='dense') - 1
    print df
    
       0  1  2
    0  0  0  3
    1  0  1  2
    2  0  1  3
    3  1  1  1
    4  2  2  5
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 2011-10-05
      • 2018-07-04
      • 1970-01-01
      • 2013-09-15
      相关资源
      最近更新 更多