Pandas Get Sequence of 1s and 0s Given Strings

为君一笑 提交于 2021-02-10 23:19:45

问题


Given the following:

import pandas as pd
df = pd.DataFrame({'a':['K','1','1,2,3']})
df
       a
0      K
1      1
2  1,2,3

I would like to convert the values in column a to a corresponding sequence of 1s and 0s given this map:

K 1 2 3 4 5
1 1 1 1 1 1

If a value is present, a 1 is put in place of a 0. If the value is not present, the place is held by a 0. If no value is present, the sequence would be a string of 6 0s.

So "K" would be: 100000

And "1,2,3" would be: 011100

Desired result:

       a       b
0      K  100000
1      1  010000
2  1,2,3  011100

I tried pd.get_dummies(df['a']), but it that only works where there is only 1 character in the cell.

Thanks in advance!


回答1:


I hope I understood your question well, but you can use .apply() with custom map:

m = {'K': 1 << 0,
     '1': 1 << 1,
     '2': 1 << 2, 
     '3': 1 << 3,
     '4': 1 << 4,
     '5': 1 << 5}
    
df['b'] = df.a.apply(
        lambda x: '{:06b}'.format(sum(m[v] for v in x.split(',')))[::-1]
    )
print(df)

Prints:

       a       b
0      K  100000
1      1  010000
2  1,2,3  011100



回答2:


Let us try get_dummies then reindex

s = df.a.str.get_dummies(',').reindex(columns=['K','1','2','3','4','5'],fill_value=0).astype(str).agg(''.join,1)
0    100000
1    010000
2    011100
dtype: object
df['b'] = s


来源:https://stackoverflow.com/questions/64287044/pandas-get-sequence-of-1s-and-0s-given-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!