【问题标题】:where is the error in Pandas crosstab queryPandas 交叉表查询中的错误在哪里
【发布时间】:2020-09-14 10:42:27
【问题描述】:

我有一个包含crosstab 查询的 Python 函数,但系统崩溃并显示以下错误:

ValueError: If using all scalar values, you must pass an index

DF 样本:

预期结果:

event_type      watch movie stay at home swimming   camping  meeting
event_location
loc1            0              65           0       254      13
loc2           60              0           125      19
loc3          518              3           705      87
loc4          721              11          318      147
loc5            0             103            0      214      17

在调试过程中显示item1item2 分配正确。

代码:

def event_loc(self,df,items):
    for item in items:
        item1 = items[0]
        item2 = items[1]
    df_event_loc_crosstab = pd.crosstab(item1, item2)
    print(df_event_loc_crosstab)

【问题讨论】:

  • 哪一行出错了?
  • 这一行df_event_loc_crosstab = pd.crosstab(item1, item2)
  • 您发布的表格中的 item1 和 item 2 是什么?
  • 我问了另一个关于错误更详细的问题,这是链接 [stackoverflow.com/questions/63899636/…
  • item1 = event_type item2=event_location

标签: python pandas for-loop crosstab


【解决方案1】:

Crosstab 应该先传递一个索引:

df = df.set_index('event_type ')    
df_event_loc_crosstab = pd.crosstab(event_type , event_location)

【讨论】:

  • 好的,我添加了索引它显示以下错误:df_event_loc_crosstab = pd.crosstab(item1,item2,index=[0]) TypeError: crosstab() got multiple values for argument 'index'
  • 一列应该是索引,例如item1 和第二个应该是常规列。删除“index=[0]”
  • 我试过你的答案,但仍然是同样的错误:df_event_mohafazat_crosstab = pd.crosstab(item1,item2,index=item1) 但仍然是同样的错误
  • 请发布 DF 样本
  • 我试过你的答案它现在显示另一个错误:代码:def event_mouhafaza(self,df,items): for item in items: item1 = items[0] item2 = items[1] df = df.set_index(item1) df_event_mohafazat_crosstab = pd.crosstab(item1,item2) print(df_event_mohafazat_crosstab) 错误:raise ValueError("If using all scalar values, you must pass an index") ValueError: If using all scalar values, you must pass an index
猜你喜欢
  • 2014-06-18
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 2011-03-01
相关资源
最近更新 更多