Home > Software engineering >  Split a matrix and save in separate lists or arrays in python?
Split a matrix and save in separate lists or arrays in python?

Time:06-26

How to create multiple data frames from this in python:

c1  c2  c3 ... c50
1   2   33 ... 46
5   8   93 ... 456
6   9   33 ... 456
7   2   32 ... 434

I want to create new arrays in this way: the c1 and c2, the c1 and c3, the c1 and c4, the c1 and c5, similarly c1 and c50. Each columns group should be save in separate df with the name of the column that change. How can i do in python?

CodePudding user response:

You can use a list comprehension:

[df[["c1", f"c{i}"]] for i in range(2, 51)]

The first two dataframes will look like:

   c1  c2
0   1   2
1   5   8
2   6   9
3   7   2

   c1  c3
0   1  33
1   5  93
2   6  33
3   7  32

CodePudding user response:

here is one way to do it. IIUC that the result will be DFs. if you need to make an array, you can use append either ".values" or ".to_numpy()" to the end of filter

for col in df.columns[1:]:
    vars()['df' col] = df.filter(['c1',col])
    print(vars()['df' col])

it results in dataframes created by names as dfc1, dfc2, dfc50. That you can access

   c1  c2
0   1   2
1   5   8
2   6   9
3   7   2
   c1  c3
0   1  33
1   5  93
2   6  33
3   7  32
   c1  c50
0   1   46
1   5  456
2   6  456
3   7  434
  • Related