python-3.x - Pandas 数据框列名似乎错误
问题描述
我是学生,因此是新手。我正在尝试按旧金山社区创建一个 Pandas 犯罪统计数据框。我的问题是我希望列名只是“邻居”和“计数”。相反,我似乎被一个单独的行卡住了,上面写着“('Neighborhood','count')”而不是正确的标签。这是代码:
df_counts = df_incidents.copy()
df_counts.rename(columns={'PdDistrict':'Neighborhood'}, inplace=True)
df_counts.drop(['IncidntNum', 'Category', 'Descript', 'DayOfWeek', 'Date', 'Time', 'Location', 'Resolution', 'Address', 'X', 'Y', 'PdId'], axis=1, inplace=True)
df_totals=df_counts.groupby(['Neighborhood']).agg({'Neighborhood':['count']})
df_totals.columns = list(map(str, df_totals.columns)) # Not sure if I need this
df_totals
输出:
('Neighborhood', 'count')
Neighborhood
BAYVIEW 14303
CENTRAL 17666
INGLESIDE 11594
MISSION 19503
NORTHERN 20100
PARK 8699
RICHMOND 8922
SOUTHERN 28445
TARAVAL 11325
TENDERLOIN 9942
解决方案
这里不需要agg()
,你可以简单地做:
df_totals = df_counts.groupby(['Neighborhood']).count()
df_totals.columns = ['count']
df_totals = df_totals.reset_index() # flatten the column headers
如果你想打印没有数字索引的输出:
print(df_totals.to_string(index=False))
推荐阅读
- localization - 如何在 tvml 应用程序中使用当前语言使用 tvjs 进行本地化
- c - 将随机索引挑选到排序数组中
- jquery - 恭喜模态不弹出
- python - 将单维数据框转换为表格形式
- c++ - 仅具有(读/写)内存顺序的内存排序或读-修改-写操作
- python - 在 Python for 循环中,如何为绘图创建图例?
- c# - Visual C# 中带有 Crystal Report 的动态表
- javascript - JavaScript:TypeError 无法读取未定义的属性“toLowerCase”?
- primefaces - p:单击时不显示对话框
- php - 如果未在 php 中设置表单值,则执行条件