Spedo
Spedo

Reputation: 365

Extracting features from a dataframe and converting them to other dataframe?

I have a datafarme (my_data:) as follows:

   my_data:        
                    0            ...              16
      TB1     [1, 5, 24, 1]      ...        [0, 0, 0, 31]
      TB2     [7, 4, 13, 1]      ...        [0, 0, 0, 25]
      TB3     [7, 6, 20, 0]      ...        [7, 4, 2, 20]
      ...       .......          ...          ........

As it can be seen, in each column there is a list of numbers, in total I have 16 columns in my_data which contain a list of numbers. Now, I want to extract those lists and use them as regular columns. So my desired my_data should be something like this:

   my_data:
             0  1  2   3  ...  60  61 62
      TB1    1, 5, 24, 1  ...  0,  0, 31
      TB2    7, 4, 13, 1  ...  0,  0, 25
      TB3    7, 6, 20, 0  ...  4,  2, 20
      ...       .......   ...   ........

Any idea?

Upvotes: 1

Views: 488

Answers (2)

jezrael
jezrael

Reputation: 862731

Convert DataFrame to 2d array with reshape and create new DataFrame by constructor:

df = pd.DataFrame(np.array(df.values.tolist()).reshape(len(df), -1), index=df.index)
print (df)
     0  1   2  3  4  5  6   7
TB1  1  5  24  1  0  0  0  31
TB2  7  4  13  1  0  0  0  25
TB3  7  6  20  0  7  4  2  20

Upvotes: 2

yatu
yatu

Reputation: 88236

One simple way is to sum along axis 1 and construct a new dataframe:

pd.DataFrame(df.sum(1).values.tolist(), index=df.index)

     0  1   2  3  4  5  6   7
TB1  1  5  24  1  0  0  0  31
TB2  7  4  13  1  0  0  0  25
...

Upvotes: 2

Related Questions