如何在Pandas中将这两列转换为正式列?

2024-10-06 12:27:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个计算旧金山每个街区的犯罪总数的项目,我使用了下面的代码,但是当我尝试使用crime\u counts.dtypes验证它时,它没有将neighbource列识别为列

import pandas as pd 
file_name='https://cocl.us/sanfran_crime_dataset'
df=pd.read_csv(file_name)
crime_count = df["PdDistrict"].value_counts().to_frame('C').rename_axis('Neighbourhood')
crime_count = crime_count.rename(columns = {"PdDistrict":"Neighbourhood"})
crime_count = crime_count.rename(columns = {"C":"Counts"})
crime_count

我想创建一个dataframe,它同时识别邻域和列


Tags: columns项目代码namedfcountfilepd
1条回答
网友
1楼 · 发布于 2024-10-06 12:27:44

首先将索引名更改为rename_axis,然后使用参数nameSeries转换为2列DataFrame

crime_count = (df["PdDistrict"].value_counts()
                               .rename_axis('Neighbourhood')
                               .reset_index(name='Counts'))
print (crime_count)
  Neighbourhood  Counts
0      SOUTHERN   28445
1      NORTHERN   20100
2       MISSION   19503
3       CENTRAL   17666
4       BAYVIEW   14303
5     INGLESIDE   11594
6       TARAVAL   11325
7    TENDERLOIN    9942
8      RICHMOND    8922
9          PARK    8699

相关问题 更多 >