如何在pandas中运行循环

时间:2017-11-06 00:25:43

标签: python pandas

我正在开设一门课程并希望使用for循环创建各种数据框,其目的是创建一个列表,然后将每个df添加到列表中。但是,下面有错误:

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)
{{1}}

2 个答案:

答案 0 :(得分:1)

在熊猫中,我们通常会这样做..

l=[]

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

您编码错误

county_df['STNAME']=state)

应该是

county_df['STNAME']==state)

基于我的理解

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

答案 1 :(得分:0)

我总是将我的Pandas DataFrame转换为列表:

my_dataframe.values.tolist()