Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

python - Pandas: reshaping data

I have a pandas Series which presently looks like this:

14    [Yellow, Pizza, Restaurants]
...
160920                  [Automotive, Auto Parts & Supplies]
160921       [Lighting Fixtures & Equipment, Home Services]
160922                 [Food, Pizza, Candy Stores]
160923           [Hair Removal, Nail Salons, Beauty & Spas]
160924           [Hair Removal, Nail Salons, Beauty & Spas]

And I want to radically reshape it into a dataframe that looks something like this...

      Yellow  Automotive  Pizza
14       1         0        1
…           
160920   0         1        0
160921   0         0        0
160922   0         0        1
160923   0         0        0
160924   0         0        0

ie. a logical construction noting which categories each observation(row) falls into.

I'm capable of writing for loop based code to tackle the problem, but given the large number of rows I need to handle, that's going to be very slow.

Does anyone know a vectorised solution to this kind of problem? I'd be very grateful.

EDIT: there are 509 categories, which I do have a list of.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
In [9]: s = Series([list('ABC'),list('DEF'),list('ABEF')])

In [10]: s
Out[10]: 
0       [A, B, C]
1       [D, E, F]
2    [A, B, E, F]
dtype: object

In [11]: s.apply(lambda x: Series(1,index=x)).fillna(0)
Out[11]: 
   A  B  C  D  E  F
0  1  1  1  0  0  0
1  0  0  0  1  1  1
2  1  1  0  0  1  1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...