1

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)
3
  • 2
    In your code array shouldn't be list? Commented Nov 6, 2017 at 0:57
  • 1
    Avoid shadowing reserved words like list. Commented Nov 6, 2017 at 1:05
  • I think this is a duplicate of stackoverflow.com/q/11633421/1240268 Commented Nov 6, 2017 at 1:32

2 Answers 2

1

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,:]
Sign up to request clarification or add additional context in comments.

3 Comments

can also do with a list comprehension :)
This doesn't explain the keyword can't be an expression hmmm
Ah, gotcha, so county_df['STNAME'] is trying to be passed as a keyword argument to .where
0

I always convert my Pandas DataFrame to list by:

my_dataframe.values.tolist()

Comments

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.