我尝试在replit中运行以下代码:
df_cat = pd.melt(df, id_vars='cardio', value_vars=['active', 'alco', 'cholesterol', 'gluc', 'overweight', 'smoke'])
c = df_cat.groupby(['cardio','variable','value'], as_index=False,level=None, sort=True, group_keys=True, observed=False).size()
cardio_0 = c[c['cardio']==0]
cardio_1 = c[c['cardio']==1]
这段代码在pycharm中运行得很好,但在replit中不起作用,我不知道还能做什么。
Traceback (most recent call last):
File "main.py", line 6, in <module>
medical_data_visualizer.draw_cat_plot()
File "/home/runner/boilerplate-medical-data-visualizer/medical_data_visualizer.py", line 33, in draw_cat_plot
cardio_0 = c(c['cardio']==0)
File "/home/runner/boilerplate-medical-data-visualizer/venv/lib/python3.8/site-packages/pandas/core/series.py", line 1071, in __getitem__
result = self.index.get_value(self, key)
File "/home/runner/boilerplate-medical-data-visualizer/venv/lib/python3.8/site-packages/pandas/core/indexes/multi.py", line 1510, in get_value
raise e1
File "/home/runner/boilerplate-medical-data-visualizer/venv/lib/python3.8/site-packages/pandas/core/indexes/multi.py", line 1494, in get_value
return self._engine.get_value(s, k)
File "pandas/_libs/index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 88, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 670, in pandas._libs.index.BaseMultiIndexCodesEngine.get_loc
KeyError: 'cardio'
同样的代码在pycharm中也能很好地工作
1条答案
按热度按时间xxslljrj1#
您可以使用
c.reset_index()
重置c
的索引,这将为MultiIndex
的每个级别创建一个列的新DataFrame,并允许您使用'cardio'
列为c
建立索引,就像您当前正在做的那样。