I have a pandas data frame (X11) like this: In actual I have 99 columns up to dx99
dx1 dx2 dx3 dx4
0 25041 40391 5856 0
1 25041 40391 25081 5856
2 25041 40391 42822 0
3 25061 40391 0 0
4 25041 40391 0 5856
5 40391 25002 5856 3569
I want to create additional column(s) for cell values like 25041,40391,5856 etc. So there will be a column 25041 with value as 1 or 0 if 25041 occurs in that particular row in any dxs columns. I am using this code and it works when number of rows are less.
mat = X11.as_matrix(columns=None)
values, counts = np.unique(mat.astype(str), return_counts=True)
for x in values:
X11[x] = X11.isin([x]).any(1).astype(int)
I am getting result like this:
dx1 dx2 dx3 dx4 0 25002 25041 25061 25081 3569 40391 42822 5856
25041 40391 5856 0 0 0 1 0 0 0 1 0 1
25041 40391 25081 5856 0 0 1 0 1 0 1 0 1
25041 40391 42822 0 0 0 1 0 0 0 1 1 0
25061 40391 0 0 0 0 0 1 0 0 1 0 0
25041 40391 0 5856 0 0 1 0 0 0 1 0 1
40391 25002 5856 3569 0 1 0 0 0 1 1 0 1
When number of rows are many thousands or in millions, it hangs and takes forever and I am not getting any result. Please see that cell values are not unique to column, instead repeating in multi columns. For ex, 40391 is occurring in dx1 as well as in dx2 and so on for 0 and 5856 etc. Any idea how to improve the logic mentioned above?