首页 > 解决方案 > 无法理解 .mode() 在 python 中的使用

问题描述

我有一个要求,我需要找出最受欢迎的开始时间。以下是帮助我找到正确解决方案的代码。

import time
import pandas as pd
import numpy as np

# bunch of code comes
# here
# that help in reaching the following steps

df = pd.read_csv(CITY_DATA[selected_city])

# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])

# extract hour from the Start Time column to create an hour column
df['hour'] = df['Start Time'].dt.hour

# extract month and day of week from Start Time to create new columns
df['month'] = df['Start Time'].dt.month

df['day_of_week'] = df['Start Time'].dt.weekday_name

# find the most popular hour
popular_hour = df['hour'].mode()[0]

这是我尝试运行此查询时得到的示例 o/p

“打印(df ['小时'])”

0         15
1         17
2          8
3         13
4         14
5          9
6          9
7         17
8         16
9         17
10         7
11        17
Name: hour, Length: 300000, dtype: int64

我使用时得到的 o/p

打印(类型(df ['小时']))

<class 'pandas.core.series.Series'>

最受欢迎的开始时间的值存储在popular_hour中,等于“17”(这是正确的值)

但是我无法理解 .mode()[0] 的部分

这个 .mode() 做什么以及为什么 [0] ?

同样的概念是计算流行的月份和流行的星期几,而不考虑它们的数据类型

标签: pythonpandasseriesmode

解决方案


mode返回一个系列:

df.mode()
0    17
dtype: int64

从此,您通过调用获取第一个项目

df.mode()[0]
17

请注意,总是返回一个系列,有时如果模式有多个值,它们都会被返回:

pd.Series([1, 1, 2, 2, 3, 3]).mode()
0    1
1    2
2    3
dtype: int64

您仍然会每次都取第一个值并丢弃其余的值。请注意,当返回多个模式时,它们始终是排序的。

阅读文档以mode获取更多信息。


推荐阅读