1

I have a dataframe like this:

name   time    session1    session2    session3
Alex   135      10             3           5
Lee    136       2             6           4

I want to make multiple dataframes based on each session. for example, i want to make dataframe one that has name, time, and session1. and dataframe 2 has name, time, and session2. and dataframe 3 has name, time, and session3. I want to use for loop or any other way is better but don't know how to choose column 1,2,3 at one time but column 1,2, 4 and etc. Any one has idea about that. The data is saved in pandas dataframe. I just don't know how to type it in Stackoverflow here. Thank you

2 Answers 2

1

I don't think you need to create a new dictionary for that.

Just directly slice your data frame whenever needed.

df[['name', 'time', 'session 1']]

If you think the following design can help you, you can set the name and time to be indexes (df.set_index(['name', 'time'])) and just simply

df['session 1']
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! this helps a lot! I prefore the way of setting index!
1

Organize it into a dictionary of dataframes:

dict_of_dfs = {f'df {i}':df[['name','time', i]] for i in df.columns[2:]}

Then you can access each dataframe as you would any other dictionary values:

>>> dict_of_dfs['df session1']
   name  time  session1
0  Alex   135        10
1   Lee   136         2
>>> dict_of_dfs['df session2']
   name  time  session2
0  Alex   135         3
1   Lee   136         6

2 Comments

I have a question about what is f'df {i}' means? I tried this but get an error about invalid syntax?
That's an f-string, which is available from python 3.6 onward. You could use 'df {}'.format(i) instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.