Darshil Shah
Darshil Shah

Reputation: 11

How to create an array of pandas dataframe in loop

Here is my code. In which CROPS & CITY are lists contains names of crops and cities in the dataframe named df. I want to divide my single dataframe 'df' into multiple dataframes for each crops and city value. and want to store them in dataframes array for that what I should put in place of XYZ?

for crop in CROPS:
  for city in CITY:

    XYZ = df.loc[(df['Commodity.Name'] == 'crops') & (df['City.Name'] == 'city')]

Upvotes: 0

Views: 2907

Answers (1)

Zoro
Zoro

Reputation: 423

Declare an empty list outside of the loop and keep on appending the filtered DataFrames to the list, like:

list_of_filtered_df = []
for crop in CROPS:
  for city in CITY:
    list_of_filtered_df.append(df.loc[(df['Commodity.Name'] == 'crops') & (df['City.Name'] == 'city')])

list_of_filtered contains the filtered DataFrames.

Upvotes: 1

Related Questions