【问题标题】:Pandas: Cannot do positional indexing熊猫:无法进行位置索引
【发布时间】:2020-09-01 14:55:32
【问题描述】:

使用美国人口普查局的人口普查数据。县是美国各州的政治和地理分区。此数据集包含 2010 年至 2015 年美国各县和州的人口数据。

    cdf = pd.read_csv('census.csv')
    cdf = cdf[cdf['SUMLEV']==50]
    cdf.head()
    def answer_five():
        count = pd.DataFrame(cdf['STNAME'].unique(), columns =["State"])
        count['ct'] = 0
        i=0
        for item in cdf['STNAME']:
            if(item == count.iloc(i)['State']):
                count.iloc(i)['ct'] += 1
            else:
                i=i+1
        return count['State'] == count['State', np.max(count['ct'])]
    answer_five()

有人可以帮我找出嵌套在 for 循环中的 if else 语句中的错误吗? 我想在不使用 groupby 的情况下解决它

【问题讨论】:

  • 你应该看看Series.value_counts。无需手动执行此操作。
  • 您可以添加并突出显示所需的输出。它将帮助其他人回答这个问题。

标签: python pandas dataframe pandas-groupby series


【解决方案1】:

pandas 中的 iloc 函数使用括号来获取实际值。不是括号。应该是:

if(item == count.iloc[i]['State']):
            count.iloc[i]['ct'] += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-21
    • 2020-06-30
    • 2020-02-04
    • 2021-12-03
    • 2014-10-11
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多