Steve Cheung
Steve Cheung

Reputation: 107

How to run for loop in pandas

I am doing a coursera course and want to create various dataframe using for loop, the idea is to create a list and then add each df into the list. However, below come back with error:

File "<ipython-input-10-2863e455a5c5>", line 7
    array.append(county_df.where(county_df['STNAME']=state))
                                ^
SyntaxError: keyword can't be an expression

census_df = pd.read_csv('census.csv')
county_df=census_df[census_df['SUMLEV'] == 50]
county_df.head()
county_df['STNAME'].unique()
list = []
print type(list)
for state in county_df['STNAME'].unique():
    array.append(county_df.where(county_df['STNAME']=state))

print (list)

Upvotes: 1

Views: 1016

Answers (2)

Data Miner
Data Miner

Reputation: 16

I always convert my Pandas DataFrame to list by:

my_dataframe.values.tolist()

Upvotes: 0

BENY
BENY

Reputation: 323376

In pandas we usually do this ..

l=[]

for _, df1 in county_df.groupby('STNAME'):
    l.append(df1)

You code error

county_df['STNAME']=state)

should be

county_df['STNAME']==state)

And base on my understanding

county_df.loc[county_df['STNAME']==state,:]

Upvotes: 1

Related Questions