1

I wanted to create multiple dataframe and make them into a list of dataframe. I wanted to split it by specifying the veh value. For example, from the datadrame below, I wanted to get 4 single dataframe:

  1. ped value 1 with veh value 1
  2. ped value 1 with veh value 2
  3. ped value 1 with veh value 3
  4. ped value 1 with veh value 4
ped value veh value
1 1
1 1
1 2
1 2
1 3
1 3
1 4
1 4

Wanted output: | ped value| veh value| | --------------------| | 1 | 1 | | 1 | 1 |

ped value veh value
1 2
1 2
ped value veh value
1 3
1 3
ped value veh value
1 4
1 4

grouped = df.groupby(['ped', 'veh']) ped_veh1 = grouped.get_group(("P1", 1)) print(ped_veh1)

The code above is the initial code i used to split the dataframe. However, I got 100 different veh value so is there any way to achieve the output as above?

I have tried using for i in range method:

for i in range (1,100): grouped = df.groupby(['ped', 'veh']) ped_veh1 = grouped.get_group(("P1", i)) print(ped_veh1)

However, the code does not work because the value i is not continuous for example: i = 1,2,3,5,6,8,9,10,12

The code stop running when they can't find i = 4 and error is raised.

So, is there any way or solution to solve this problem?

jayjay
  • 11
  • 3

1 Answers1

0

You can use split Pandas Dataframe using groupby() function then get_group

dfs = []
for v in df['veh value'].unique():
    dfs.append(df.groupby('veh value').get_group(v))
  • Output
[   ped value  veh value
 0          1          1
 1          1          1,
    ped value  veh value
 2          1          2
 3          1          2,
    ped value  veh value
 4          1          3
 5          1          3,
    ped value  veh value
 6          1          4
 7          1          4]
Mohamed Desouky
  • 4,340
  • 2
  • 4
  • 19