Pandas DataFrame将字符串路径映射到整数路径

时间:2014-05-24 07:34:52

标签: python string pandas dataframe

我有一只大熊猫DataFrame喜欢跟随。

In [22]: df = pd.DataFrame({'id' : [1,2,3,4,5,6,7],
                'path'  : ["abc,cde,eg,ba","abc,cde,ba","abc,yz,zx,eg","abc,cde,eg,ba","abc,cde","abc","cde,eg,ba"]})

In [23]: df
Out[23]: 
   id           path
0   1  abc,cde,eg,ba
1   2     abc,cde,ba
2   3   abc,yz,zx,eg
3   4  abc,cde,eg,ba
4   5        abc,cde
5   6            abc
6   7      cde,eg,ba

我想将路径中的所有这些字符串映射到整数。

abc = 1, cde = 2, eg = 3, ba = 4, yz = 5, zx = 6

最后我需要得到以下输出。

    id  path
0   1  1234
1   2  124
2   3  1563
3   4  1234
4   5  12
5   6  1
6   7  234

1 个答案:

答案 0 :(得分:1)

这是我要做的事情

import pandas as pd
df = pd.DataFrame({'id' : [1,2,3,4,5,6,7],
        'path'  : ["abc,cde,eg,ba","abc,cde,ba","abc,yz,zx,eg",\
                   "abc,cde,eg,ba","abc,cde","abc","cde,eg,ba"]})
d = {'abc':'1', 'cde':'2', 'eg':'3', 'ba':'4', 'yz':'5', 'zx':'6'}
df['path'] = df['path'].apply(lambda x:int(''.join([d[i] for i in x.split(',')])))