0

I need to create multiple dataframes from slices of a bigger dataframe in pandas based on a condition. The different dataframes have to be named on the basis of some row values of the big dataframe.

This is the big dataframe:

 Id  Valore
ID554    53.0
ID554    43.0
ID522    42.0
ID522    32.0
ID566    26.0

therefore the different dataframes have to be named ID554, ID522, ID566 and so on. I have tried this:

id=df['Id'].unique()
for a in id:
 a=df.loc[(df['ID']==a)]

it does not work though..

2 Answers 2

1

You can use .groupby:

dataframes = {}
for name, g in df.groupby("Id"):
    dataframes[name] = g

# print the data:
for k, v in dataframes.items():
    print("Name:", k)
    print("-" * 80)
    print(v)
    print()

Prints:

Name: ID522
--------------------------------------------------------------------------------
      Id  Valore
2  ID522    42.0
3  ID522    32.0

Name: ID554
--------------------------------------------------------------------------------
      Id  Valore
0  ID554    53.0
1  ID554    43.0

Name: ID566
--------------------------------------------------------------------------------
      Id  Valore
4  ID566    26.0
Sign up to request clarification or add additional context in comments.

Comments

0

Use exec

df = pd.DataFrame({"Id":["ID554","ID554","ID522","ID522","ID566"],"Valore":[53,43,42,32,26]})

for i in df.Id.unique():
    exec(f"{i} = df[df.Id == i]")

Following code will make different dataframes and save it in different variables with the name of its ID.

OUTPUTS:

print(ID522)

          Id  Valore
    2  ID522      42
    3  ID522      32

print(ID554)

       Id  Valore
    0  ID554      53
    1  ID554      43

print(ID566)

       Id  Valore
    4  ID566      26

3 Comments

Using exec is almost always a bad idea. There are too many ways to go wrong.
Requirement is having multiple sub dataframes with the name of ID.
Another approach can be making a dict to store those dataframes but that is not required

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.