gpt4 book ai didi

python - 如何在 pandas 中运行 for 循环

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:14 26 4
gpt4 key购买 nike

我正在做 coursera 类(class),想要使用 for 循环创建各种数据帧,其想法是创建一个列表,然后将每个 df 添加到列表中。但是,下面返回错误:

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)

最佳答案

在 pandas 中我们通常这样做..

l=[]

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

您的代码错误

county_df['STNAME']=州)

应该是

county_df['STNAME']==州)

根据我的理解

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

关于python - 如何在 pandas 中运行 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com