【问题标题】:Type Error when trying to subset data frame尝试对数据框进行子集化时出现类型错误
【发布时间】:2019-09-29 21:47:15
【问题描述】:

我正在尝试根据列的值创建数据框的子集。但是,当我运行我的代码时,出现以下错误

TypeError: 'Series' 对象是可变的,因此它们不能被散列。

我的代码如下,谢谢!

#read data
df = pd.read_csv('Workbook.csv')

#turn certain columns into categories
df['Class'] = df['Class'].astype('category')
df['Pos'] = df['Pos'].astype('category')
df['Drafted'] = df['Drafted'].astype('category')

#subset of undrafted players
df_sosByDrafted = df[['SOS','Drafted']]
df_sos_undrafted = df_sosByDrafted.loc(df_sosByDrafted['Drafted'] == 0)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    .loc之后需要使用方括号!

    df_sos_undrafted = df_sosByDrafted.loc[df_sosByDrafted['Drafted'] == 0]
    

    【讨论】:

      【解决方案2】:

      如果我正确理解了您的目标,您可以使用以下代码行获取所有行的子集(仅在 SOS 和 Drafted 列的子集中),在 Drafted 列中值为 0:

      df_sos_undrafted = df_sosByDrafted[ df_sosByDrafted[ 'Drafted' ] == 0 ]
      

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-07
        相关资源
        最近更新 更多