赞
踩
目录
294、pandas.Series.dt.month_name方法
295、pandas.Series.dt.day_name方法
- # 291、pandas.Series.dt.round函数
- pandas.Series.dt.round(*args, **kwargs)
- Perform round operation on the data to the specified freq.
-
- Parameters:
- freq
- str or Offset
- The frequency level to round the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). See frequency aliases for a list of possible freq values.
-
- ambiguous
- ‘infer’, bool-ndarray, ‘NaT’, default ‘raise’
- Only relevant for DatetimeIndex:
-
- ‘infer’ will attempt to infer fall dst-transition hours based on order
-
- bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
-
- ‘NaT’ will return NaT where there are ambiguous times
-
- ‘raise’ will raise an AmbiguousTimeError if there are ambiguous times.
-
- nonexistent
- ‘shift_forward’, ‘shift_backward’, ‘NaT’, timedelta, default ‘raise’
- A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
-
- ‘shift_forward’ will shift the nonexistent time forward to the closest existing time
-
- ‘shift_backward’ will shift the nonexistent time backward to the closest existing time
-
- ‘NaT’ will return NaT where there are nonexistent times
-
- timedelta objects will shift nonexistent times by the timedelta
-
- ‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
-
- Returns:
- DatetimeIndex, TimedeltaIndex, or Series
- Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
-
- Raises:
- ValueError if the
- freq
- cannot be converted.
- Notes
-
- If the timestamps have a timezone, rounding will take place relative to the local (“wall”) time and re-localized to the same timezone. When rounding near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.

291-2-1、freq(必须):str or DateOffset,指定要四舍五入到的时间频率,常见的频率字符串包括:
291-2-2、ambiguous(可选,默认值为'raise'):用于处理夏令时转换时的模棱两可的时间。默认情况下,如果时间不明确,会引发错误。可以选择以下选项之一:
291-2-3、nonexistent(可选,默认值为'raise'):用于处理不存在的时间,例如从夏令时到标准时间的转换。默认情况下,如果时间不存在,会引发错误。可以选择以下选项之一:
用于将datetime数据四舍五入到最近的指定频率。例如,可以将datetime数据四舍五入到最近的秒、分钟、小时等,这对于需要标准化时间戳数据或进行时间间隔计算时非常有用。
返回一个新的Series,其中包含四舍五入到指定频率的datetime数据。
使用场景:
291-5-1、数据标准化和对齐:在处理时间序列数据时,经常需要将时间戳对齐到统一的频率,以便进行进一步的分析和处理。例如,将不同时间戳对齐到最近的整点、整分或整秒,以便对不同时间序列进行比较或合并。
291-5-2、处理高频数据:在金融数据分析中,经常会处理高频交易数据,为了简化分析过程,可以将这些高频数据(如毫秒级别的交易数据)四舍五入到秒、分钟或小时级别,以便于观察趋势和模式。
291-5-3、生成时间窗口:在生成固定长度的时间窗口时,可以使用该方法将时间戳四舍五入到最近的窗口边界。例如,在生成按分钟分组的窗口时,可以将时间戳四舍五入到最近的分钟。
291-5-4、数据清理和预处理:在数据清理过程中,经常需要处理不精确的时间戳数据,通过将时间戳四舍五入到最近的标准时间,可以消除小的误差,使数据更加整洁和一致。
291-5-5、数据聚合:在对时间序列数据进行聚合操作(如计算平均值、总和等)之前,通常需要将时间戳对齐到同一频率。例如,在按小时聚合数据时,可以先将时间戳四舍五入到最近的小时。
无
- # 291、pandas.Series.dt.round方法
- # 291-1、天气数据分析
- import pandas as pd
- # 创建示例天气数据
- weather_data = pd.DataFrame({
- 'timestamp': pd.to_datetime([
- '2024-08-07 14:35:29', '2024-08-07 14:35:45', '2024-08-07 14:36:12'
- ]),
- 'temperature': [25.3, 25.5, 25.7]
- })
- # 将时间戳四舍五入到最近的分钟
- weather_data['rounded_timestamp'] = weather_data['timestamp'].dt.round('min')
- # 按照四舍五入后的时间戳计算每分钟的平均温度
- average_temperature_per_minute = weather_data.groupby('rounded_timestamp')['temperature'].mean().reset_index()
- print("每分钟的平均温度:")
- print(average_temperature_per_minute, end='\n\n')
-
- # 291-2、交通流量分析
- import pandas as pd
- # 创建示例交通流量数据
- traffic_data = pd.DataFrame({
- 'timestamp': pd.to_datetime([
- '2024-08-07 08:15:12', '2024-08-07 08:16:45', '2024-08-07 08:17:59'
- ]),
- 'vehicle_count': [15, 20, 25]
- })
- # 将时间戳四舍五入到最近的小时
- traffic_data['rounded_timestamp'] = traffic_data['timestamp'].dt.round('h')
- # 按照四舍五入后的时间戳计算每小时的车流量总数
- vehicle_count_per_hour = traffic_data.groupby('rounded_timestamp')['vehicle_count'].sum().reset_index()
- print("每小时的车流量总数:")
- print(vehicle_count_per_hour, end='\n\n')
-
- # 291-3、股票交易数据分析
- import pandas as pd
- # 创建示例股票交易数据
- trade_data = pd.DataFrame({
- 'timestamp': pd.to_datetime([
- '2024-08-07 09:00:01.123', '2024-08-07 09:00:02.456', '2024-08-07 09:00:03.789'
- ]),
- 'trade_amount': [1000, 1500, 2000]
- })
- # 将时间戳四舍五入到最近的秒
- trade_data['rounded_timestamp'] = trade_data['timestamp'].dt.round('s')
- # 按照四舍五入后的时间戳计算每秒的交易总金额
- trade_amount_per_second = trade_data.groupby('rounded_timestamp')['trade_amount'].sum().reset_index()
- print("每秒的交易总金额:")
- print(trade_amount_per_second, end='\n\n')
-
- # 291-4、制造业生产数据分析
- import pandas as pd
- # 创建示例制造业生产数据
- production_data = pd.DataFrame({
- 'timestamp': pd.to_datetime([
- '2024-08-07 10:12:34', '2024-08-07 10:45:21', '2024-08-07 11:02:45'
- ]),
- 'quantity': [100, 200, 150]
- })
- # 将时间戳四舍五入到最近的小时
- production_data['rounded_timestamp'] = production_data['timestamp'].dt.round('h')
- # 按照四舍五入后的时间戳计算每小时的生产数量
- quantity_per_hour = production_data.groupby('rounded_timestamp')['quantity'].sum().reset_index()
- print("每小时的生产数量:")
- print(quantity_per_hour, end='\n\n')
-
- # 291-5、网站访问数据分析
- import pandas as pd
- # 创建示例网站访问数据
- visit_data = pd.DataFrame({
- 'timestamp': pd.to_datetime([
- '2024-08-07 15:03:45', '2024-08-07 15:04:15', '2024-08-07 15:04:35'
- ]),
- 'user_id': [101, 102, 103]
- })
- # 将时间戳四舍五入到最近的分钟
- visit_data['rounded_timestamp'] = visit_data['timestamp'].dt.round('min')
- # 按照四舍五入后的时间戳计算每分钟的访问量
- visit_count_per_minute = visit_data.groupby('rounded_timestamp')['user_id'].count().reset_index()
- print("每分钟的访问量:")
- print(visit_count_per_minute, end='\n\n')
-
- # 291-6、电力消耗数据分析
- import pandas as pd
- # 创建示例电力消耗数据
- power_consumption_data = pd.DataFrame({
- 'timestamp': pd.to_datetime([
- '2024-08-07 01:45:00', '2024-08-07 13:30:00', '2024-08-08 02:15:00'
- ]),
- 'power_consumption': [120, 150, 130]
- })
- # 将时间戳四舍五入到最近的一天
- power_consumption_data['rounded_timestamp'] = power_consumption_data['timestamp'].dt.round('D')
- # 按照四舍五入后的时间戳计算每天的电力消耗总量
- daily_power_consumption = power_consumption_data.groupby('rounded_timestamp')['power_consumption'].sum().reset_index()
- print("每天的电力消耗总量:")
- print(daily_power_consumption)

- # 291、pandas.Series.dt.round方法
- # 291-1、天气数据分析
- # 每分钟的平均温度:
- # rounded_timestamp temperature
- # 0 2024-08-07 14:35:00 25.3
- # 1 2024-08-07 14:36:00 25.6
-
- # 291-2、交通流量分析
- # 每小时的车流量总数:
- # rounded_timestamp vehicle_count
- # 0 2024-08-07 08:00:00 60
-
- # 291-3、股票交易数据分析
- # 每秒的交易总金额:
- # rounded_timestamp trade_amount
- # 0 2024-08-07 09:00:01 1000
- # 1 2024-08-07 09:00:02 1500
- # 2 2024-08-07 09:00:04 2000
-
- # 291-4、制造业生产数据分析
- # 每小时的生产数量:
- # rounded_timestamp quantity
- # 0 2024-08-07 10:00:00 100
- # 1 2024-08-07 11:00:00 350
-
- # 291-5、网站访问数据分析
- # 每分钟的访问量:
- # rounded_timestamp user_id
- # 0 2024-08-07 15:04:00 2
- # 1 2024-08-07 15:05:00 1
-
- # 291-6、电力消耗数据分析
- # 每天的电力消耗总量:
- # rounded_timestamp power_consumption
- # 0 2024-08-07 120
- # 1 2024-08-08 280

- # 292、pandas.Series.dt.floor函数
- pandas.Series.dt.floor(*args, **kwargs)
- Perform floor operation on the data to the specified freq.
-
- Parameters:
- freq
- str or Offset
- The frequency level to floor the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). See frequency aliases for a list of possible freq values.
-
- ambiguous
- ‘infer’, bool-ndarray, ‘NaT’, default ‘raise’
- Only relevant for DatetimeIndex:
-
- ‘infer’ will attempt to infer fall dst-transition hours based on order
-
- bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
-
- ‘NaT’ will return NaT where there are ambiguous times
-
- ‘raise’ will raise an AmbiguousTimeError if there are ambiguous times.
-
- nonexistent
- ‘shift_forward’, ‘shift_backward’, ‘NaT’, timedelta, default ‘raise’
- A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
-
- ‘shift_forward’ will shift the nonexistent time forward to the closest existing time
-
- ‘shift_backward’ will shift the nonexistent time backward to the closest existing time
-
- ‘NaT’ will return NaT where there are nonexistent times
-
- timedelta objects will shift nonexistent times by the timedelta
-
- ‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
-
- Returns:
- DatetimeIndex, TimedeltaIndex, or Series
- Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
-
- Raises:
- ValueError if the
- freq
- cannot be converted.
- Notes
-
- If the timestamps have a timezone, flooring will take place relative to the local (“wall”) time and re-localized to the same timezone. When flooring near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.

292-2-1、freq(必须):str or DateOffset,指定要四舍五入到的时间频率,常见的频率字符串包括:
292-2-2、ambiguous(可选,默认值为'raise'):用于处理夏令时转换时的模棱两可的时间。默认情况下,如果时间不明确,会引发错误。可以选择以下选项之一:
292-2-3、nonexistent(可选,默认值为'raise'):用于处理不存在的时间,例如从夏令时到标准时间的转换。默认情况下,如果时间不存在,会引发错误。可以选择以下选项之一:
将每个时间戳向下取整到指定的时间频率。例如,如果我们有一系列时间戳,并希望将它们对齐到最近的小时,我们可以使用floor('h')。
返回一个新的pandas.Series对象,其中的每个时间戳都被向下取整到指定频率,原始的Series对象不会被修改。
使用场景:
292-5-1、时间对齐:在进行时间序列分析时,数据可能来自不同的源,并且时间戳不完全一致,使用floor方法可以将这些时间戳对齐到统一的时间间隔,从而简化数据的合并和比较。
292-5-2、数据聚合:当需要对时间序列数据进行聚合分析时,如按小时、天、周等频率计算平均值或总和,floor方法可以帮助将时间戳对齐到这些频率,之后可以使用groupby和聚合函数进行分析。
292-5-3、异常值处理:在处理时间序列数据时,可能会遇到一些不规则的时间戳,使用floor方法可以将这些不规则的时间戳对齐到标准的时间间隔,便于后续的异常值处理。
292-5-4、缺失值填充:通过将时间序列对齐到固定的时间间隔,可以方便地识别和填充缺失值。例如,可以使用reindex方法创建一个完整的时间索引,然后填充缺失的数据。
292-5-5、滚动窗口计算:在时间序列分析中,经常需要计算滚动窗口统计量(如滚动平均值),floor方法可以帮助将时间对齐,从而简化滚动窗口计算的过程。
292-5-6、实时数据流处理:在处理实时数据流时,经常需要将数据按固定的时间间隔进行处理,floor方法可以帮助将实时数据对齐到固定的时间窗口,从而简化实时数据的处理逻辑。
无
- # 292、pandas.Series.dt.floor函数
- # 292-1、时间对齐
- import pandas as pd
- # 示例数据
- timestamps = pd.Series(pd.to_datetime(['2024-08-07 10:15:30', '2024-08-07 10:45:15', '2024-08-07 11:05:45']))
- floored_hours = timestamps.dt.floor('h')
- print(floored_hours, end='\n\n')
-
- # 292-2、数据聚合
- import pandas as pd
- # 示例数据
- data = {
- 'timestamp': pd.to_datetime(['2024-08-07 10:15:30', '2024-08-07 10:45:15', '2024-08-07 11:05:45']),
- 'value': [10, 20, 30]
- }
- df = pd.DataFrame(data)
- df['floored_hour'] = df['timestamp'].dt.floor('h')
- aggregated = df.groupby('floored_hour')['value'].sum()
- print(aggregated, end='\n\n')
-
- # 292-3、异常值处理
- import pandas as pd
- # 示例数据
- timestamps = pd.Series(pd.to_datetime(['2024-08-07 10:15:30', '2024-08-07 10:45:15', '2024-08-07 11:05:45']))
- floored_minutes = timestamps.dt.floor('min')
- print(floored_minutes, end='\n\n')
-
- # 292-4、缺失值填充
- import pandas as pd
- # 示例数据
- timestamps = pd.date_range('2024-08-07 10:00:00', periods=3, freq='h')
- values = [10, None, 30]
- df = pd.DataFrame({'timestamp': timestamps, 'value': values})
- df.set_index('timestamp', inplace=True)
- df = df.reindex(pd.date_range('2024-08-07 10:00:00', '2024-08-07 12:00:00', freq='h'))
- df['value'].fillna(method='ffill', inplace=True)
- print(df, end='\n\n')
-
- # 292-5、滚动窗口计算
- import pandas as pd
- # 示例数据
- data = pd.Series([10, 20, 30], index=pd.to_datetime(['2024-08-07 10:15:30', '2024-08-07 10:45:15', '2024-08-07 11:05:45']))
- floored_data = data.groupby(data.index.floor('h')).sum()
- rolling_mean = floored_data.rolling(window=2).mean()
- print(rolling_mean, end='\n\n')
-
- # 292-6、实时数据流处理
- import pandas as pd
- import numpy as np
- # 模拟实时数据流
- timestamps = pd.Series(pd.to_datetime(['2024-08-07 10:15:30', '2024-08-07 10:45:15', '2024-08-07 11:05:45']))
- values = pd.Series(np.random.randn(len(timestamps)))
- # 对齐到最近的分钟
- floored_minutes = timestamps.dt.floor('min')
- real_time_df = pd.DataFrame({'timestamp': floored_minutes, 'value': values})
- print(real_time_df)

- # 292、pandas.Series.dt.floor函数
- # 292-1、时间对齐
- # 0 2024-08-07 10:00:00
- # 1 2024-08-07 10:00:00
- # 2 2024-08-07 11:00:00
- # dtype: datetime64[ns]
-
- # 292-2、数据聚合
- # floored_hour
- # 2024-08-07 10:00:00 30
- # 2024-08-07 11:00:00 30
- # Name: value, dtype: int64
-
- # 292-3、异常值处理
- # 0 2024-08-07 10:15:00
- # 1 2024-08-07 10:45:00
- # 2 2024-08-07 11:05:00
- # dtype: datetime64[ns]
-
- # 292-4、缺失值填充
- # value
- # 2024-08-07 10:00:00 10.0
- # 2024-08-07 11:00:00 10.0
- # 2024-08-07 12:00:00 30.0
-
- # 292-5、滚动窗口计算
- # 2024-08-07 10:00:00 NaN
- # 2024-08-07 11:00:00 30.0
- # dtype: float64
-
- # 292-6、实时数据流处理
- # timestamp value
- # 0 2024-08-07 10:15:00 -1.294484
- # 1 2024-08-07 10:45:00 -1.846297
- # 2 2024-08-07 11:05:00 -2.314171

- # 293、pandas.Series.dt.ceil函数
- pandas.Series.dt.ceil(*args, **kwargs)
- Perform ceil operation on the data to the specified freq.
-
- Parameters:
- freq
- str or Offset
- The frequency level to ceil the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). See frequency aliases for a list of possible freq values.
-
- ambiguous
- ‘infer’, bool-ndarray, ‘NaT’, default ‘raise’
- Only relevant for DatetimeIndex:
-
- ‘infer’ will attempt to infer fall dst-transition hours based on order
-
- bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
-
- ‘NaT’ will return NaT where there are ambiguous times
-
- ‘raise’ will raise an AmbiguousTimeError if there are ambiguous times.
-
- nonexistent
- ‘shift_forward’, ‘shift_backward’, ‘NaT’, timedelta, default ‘raise’
- A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
-
- ‘shift_forward’ will shift the nonexistent time forward to the closest existing time
-
- ‘shift_backward’ will shift the nonexistent time backward to the closest existing time
-
- ‘NaT’ will return NaT where there are nonexistent times
-
- timedelta objects will shift nonexistent times by the timedelta
-
- ‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
-
- Returns:
- DatetimeIndex, TimedeltaIndex, or Series
- Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
-
- Raises:
- ValueError if the
- freq
- cannot be converted.
- Notes
-
- If the timestamps have a timezone, ceiling will take place relative to the local (“wall”) time and re-localized to the same timezone. When ceiling near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.

293-2-1、freq(必须):str or DateOffset,指定要四舍五入到的时间频率,常见的频率字符串包括:
293-2-2、ambiguous(可选,默认值为'raise'):用于处理夏令时转换时的模棱两可的时间。默认情况下,如果时间不明确,会引发错误。可以选择以下选项之一:
293-2-3、nonexistent(可选,默认值为'raise'):用于处理不存在的时间,例如从夏令时到标准时间的转换。默认情况下,如果时间不存在,会引发错误。可以选择以下选项之一:
用于将时间序列中的每个时间戳向上取整到最近的指定频率。例如,如果将一个时间序列取整到小时,那么所有分钟和秒的信息都会被抹去,每个时间戳都会向上取整到下一个整点小时。
返回值是一个pandas.Series对象,包含了将原时间序列的每个时间戳向上取整到最近频率的时间戳。
使用场景:
293-5-1、数据预处理:在处理时间序列数据时,有时候需要将时间戳标准化为相同的频率,以便进行后续分析。比如,将交易数据、传感器数据等按小时或天进行汇总分析。
293-5-2、时间间隔对齐:在计算时间间隔时,可能需要将时间戳向上取整到最近的频率,以确保时间间隔的一致性。例如,在计算每日、每小时的平均值、总和等统计数据时,可以使用该函数将时间戳对齐到整点。
293-5-3、可视化:在进行时间序列数据的可视化时,将时间戳向上取整到最近的频率可以使图表更易读。例如,将数据按小时或天进行聚合后再绘图,可以减少图表的复杂度,提高可读性。
293-5-4、数据合并:在合并多个时间序列数据时,可能需要将时间戳对齐到相同的频率,以便进行合并和比较。例如,将不同来源的传感器数据合并到同一个时间轴上,可以使用该函数将所有时间戳对齐到最近的整点。
无
- # 293、pandas.Series.dt.ceil函数
- # 293-1、数据预处理
- import pandas as pd
- # 示例数据:传感器数据
- data = {
- 'timestamp': [
- '2024-08-07 08:45:00', '2024-08-07 08:50:00', '2024-08-07 09:05:00',
- '2024-08-07 09:15:00', '2024-08-07 10:05:00'
- ],
- 'value': [10, 12, 13, 15, 20]
- }
- df = pd.DataFrame(data)
- df['timestamp'] = pd.to_datetime(df['timestamp'])
- # 将时间戳向上取整到最近的小时
- df['rounded_timestamp'] = df['timestamp'].dt.ceil('h')
- # 按小时汇总数据
- hourly_summary = df.groupby('rounded_timestamp')['value'].sum().reset_index()
- print(hourly_summary, end='\n\n')
-
- # 293-2、时间间隔对齐
- import pandas as pd
- # 示例数据:交易数据
- trade_data = {
- 'trade_time': [
- '2024-08-07 10:15:25', '2024-08-07 10:15:35', '2024-08-07 10:15:45',
- '2024-08-07 10:16:00', '2024-08-07 10:16:20'
- ],
- 'price': [100, 101, 102, 103, 104]
- }
- trade_df = pd.DataFrame(trade_data)
- trade_df['trade_time'] = pd.to_datetime(trade_df['trade_time'])
- # 将时间戳向上取整到最近的分钟
- trade_df['aligned_time'] = trade_df['trade_time'].dt.ceil('min')
- print(trade_df, end='\n\n')
-
- # 293-3、可视化
- import matplotlib.pyplot as plt
- # 示例数据:网页访问数据
- visit_data = {
- 'visit_time': [
- '2024-08-01 12:34:56', '2024-08-01 14:22:33', '2024-08-02 09:18:45',
- '2024-08-02 10:12:34', '2024-08-03 16:45:12'
- ],
- 'visits': [1, 1, 1, 1, 1]
- }
- visit_df = pd.DataFrame(visit_data)
- visit_df['visit_time'] = pd.to_datetime(visit_df['visit_time'])
- # 将时间戳向上取整到最近的天
- visit_df['day'] = visit_df['visit_time'].dt.ceil('D')
- # 按天汇总数据
- daily_visits = visit_df.groupby('day')['visits'].sum().reset_index()
- # 可视化
- plt.figure(figsize=(10, 5))
- plt.plot(daily_visits['day'], daily_visits['visits'], marker='o')
- plt.xlabel('Date')
- plt.ylabel('Number of Visits')
- plt.title('Daily Web Visits')
- plt.grid(True)
- plt.show()
-
- # 293-4、数据合并
- import pandas as pd
- # 示例数据:传感器A数据
- sensor_a_data = {
- 'timestamp': [
- '2024-08-07 10:15:25', '2024-08-07 10:35:12', '2024-08-07 10:55:45'
- ],
- 'sensor_a_value': [0.1, 0.3, 0.5]
- }
- sensor_a_df = pd.DataFrame(sensor_a_data)
- sensor_a_df['timestamp'] = pd.to_datetime(sensor_a_df['timestamp'])
- sensor_a_df['timestamp'] = sensor_a_df['timestamp'].dt.ceil('h')
- # 示例数据:传感器B数据
- sensor_b_data = {
- 'timestamp': [
- '2024-08-07 11:05:21', '2024-08-07 11:22:33'
- ],
- 'sensor_b_value': [0.6, 0.7]
- }
- sensor_b_df = pd.DataFrame(sensor_b_data)
- sensor_b_df['timestamp'] = pd.to_datetime(sensor_b_df['timestamp'])
- sensor_b_df['timestamp'] = sensor_b_df['timestamp'].dt.ceil('h')
- # 合并数据
- merged_df = pd.merge(sensor_a_df, sensor_b_df, on='timestamp', how='outer')
- print(merged_df, end='\n\n')

- # 293、pandas.Series.dt.ceil函数
- # 293-1、数据预处理
- # rounded_timestamp value
- # 0 2024-08-07 09:00:00 22
- # 1 2024-08-07 10:00:00 28
- # 2 2024-08-07 11:00:00 20
-
- # 293-2、时间间隔对齐
- # trade_time price aligned_time
- # 0 2024-08-07 10:15:25 100 2024-08-07 10:16:00
- # 1 2024-08-07 10:15:35 101 2024-08-07 10:16:00
- # 2 2024-08-07 10:15:45 102 2024-08-07 10:16:00
- # 3 2024-08-07 10:16:00 103 2024-08-07 10:16:00
- # 4 2024-08-07 10:16:20 104 2024-08-07 10:17:00
-
- # 293-3、可视化
- # 见图1
-
- # 293-4、数据合并
- # timestamp sensor_a_value sensor_b_value
- # 0 2024-08-07 11:00:00 0.1 NaN
- # 1 2024-08-07 11:00:00 0.3 NaN
- # 2 2024-08-07 11:00:00 0.5 NaN
- # 3 2024-08-07 12:00:00 NaN 0.6
- # 4 2024-08-07 12:00:00 NaN 0.7

图1:
- # 294、pandas.Series.dt.month_name方法
- pandas.Series.dt.month_name(*args, **kwargs)
- Return the month names with specified locale.
-
- Parameters:
- locale
- str, optional
- Locale determining the language in which to return the month name. Default is English locale ('en_US.utf8'). Use the command locale -a on your terminal on Unix systems to find your locale language code.
-
- Returns:
- Series or Index
- Series or Index of month names.
294-2-1、*args(可选):其他位置参数,为后续扩展功能做预留。
294-2-2、**kwargs(可选):其他关键字参数,为后续扩展功能做预留。
294-2-2-1、locale(可选):指定返回的月份名称的语言环境。例如,“en”表示英语,“fr”表示法语。默认情况下,返回值是根据当前系统的默认语言环境生成的。
用于返回datetime类型的Series对象中每个日期的月份名称,且这些名称是以字符串的形式返回的,例如“January”、“February”等。
返回一个pandas.Series对象,其中包含每个日期的月份名称。
使用场景:
294-5-1、数据可视化:在绘制时间序列图或统计图时,可以使用月份名称来标签和分类数据,使图表更具可读性。例如,绘制每个月的销售额图表时,使用月份名称作为 x 轴标签。
294-5-2、报告和分析:在生成数据报告时,可能需要按月份分组数据。将日期转换为月份名称可以帮助更直观地展示每个月的数据汇总和趋势。
294-5-3、数据清洗和预处理:在数据清洗过程中,可能需要将时间戳数据转换为更易于分析的格式,将日期转换为月份名称可以帮助将数据按月份进行聚合或分析。
294-5-4、市场分析:对于销售数据、用户活动数据等,可以按月份进行分析,以识别季节性趋势、销售高峰期或用户行为模式。
294-5-5、客户和用户行为分析:分析客户行为时,月份名称可以帮助识别客户在不同月份的活动模式或趋势,进而调整营销策略或活动计划。
294-5-6、财务和业务计划:企业在进行财务分析和业务计划时,需要按月份跟踪和预测各种财务指标,如收入、支出和利润等。
无
- # 294、pandas.Series.dt.month_name方法
- # 294-1、数据可视化
- import matplotlib.pyplot as plt
- import pandas as pd
- # 创建示例数据
- data = {
- 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
- 'sales': [200, 220, 250, 270, 300, 320, 280, 310, 330, 340, 360, 380]
- }
- df = pd.DataFrame(data)
- # 添加月份名称列
- df['month'] = df['date'].dt.month_name()
- # 绘制图表
- plt.figure(figsize=(10, 6))
- plt.plot(df['month'], df['sales'], marker='o', color='purple')
- plt.xlabel('Month')
- plt.ylabel('Sales')
- plt.title('Monthly Sales')
- plt.xticks(rotation=45)
- plt.grid(True)
- # 添加数据标签
- for i, value in enumerate(df['sales']):
- plt.text(i, value + 5, str(value), ha='center', va='bottom', color='red', fontweight='bold') # 在每个点上方显示标签并加粗
- plt.show()
-
- # 294-2、报告和分析
- import pandas as pd
- # 创建示例数据
- data = {
- 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
- 'sales': [200, 220, 250, 270, 300, 320, 280, 310, 330, 340, 360, 380]
- }
- df = pd.DataFrame(data)
- monthly_sales = df.groupby(df['date'].dt.month_name())['sales'].sum().reset_index()
- monthly_sales.columns = ['Month', 'Total Sales']
- print(monthly_sales, end='\n\n')
-
- # 294-3、数据清洗和预处理
- import pandas as pd
- # 创建示例数据
- data = {
- 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
- 'sales': [200, 220, 250, 270, 300, 320, 280, 310, 330, 340, 360, 380]
- }
- df = pd.DataFrame(data)
- df['month_name'] = df['date'].dt.month_name()
- print(df, end='\n\n')
-
- # 294-4、市场分析
- import pandas as pd
- # 创建示例数据
- data = {
- 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
- 'sales': [200, 220, 250, 270, 300, 320, 280, 310, 330, 340, 360, 380]
- }
- df = pd.DataFrame(data)
- monthly_summary = df.groupby(df['date'].dt.month_name()).agg({
- 'sales': ['mean', 'median', 'max']
- }).reset_index()
- print(monthly_summary, end='\n\n')
-
- # 294-5、客户和用户行为分析
- import pandas as pd
- # 示例数据
- user_data = {
- 'activity_date': pd.date_range(start='2024-01-01', periods=30, freq='D'),
- 'user_id': range(1, 31)
- }
- user_df = pd.DataFrame(user_data)
- # 添加月份名称列
- user_df['month'] = user_df['activity_date'].dt.month_name()
- # 按月份统计用户活动次数
- activity_summary = user_df.groupby('month').size().reset_index(name='activity_count')
- print(activity_summary, end='\n\n')
-
- # 294-6、财务和业务计划
- import pandas as pd
- # 示例财务数据
- financial_data = {
- 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
- 'revenue': [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100]
- }
- financial_df = pd.DataFrame(financial_data)
- # 添加月份名称列
- financial_df['month'] = financial_df['date'].dt.month_name()
- # 按月份汇总收入
- monthly_revenue = financial_df.groupby('month')['revenue'].sum().reset_index()
- print(monthly_revenue)

- # 294、pandas.Series.dt.month_name方法
- # 294-1、数据可视化
- # 见图2
-
- # 294-2、报告和分析
- # Month Total Sales
- # 0 April 270
- # 1 August 310
- # 2 December 380
- # 3 February 220
- # 4 January 200
- # 5 July 280
- # 6 June 320
- # 7 March 250
- # 8 May 300
- # 9 November 360
- # 10 October 340
- # 11 September 330
-
- # 294-3、数据清洗和预处理
- # date sales month_name
- # 0 2024-01-31 200 January
- # 1 2024-02-29 220 February
- # 2 2024-03-31 250 March
- # 3 2024-04-30 270 April
- # 4 2024-05-31 300 May
- # 5 2024-06-30 320 June
- # 6 2024-07-31 280 July
- # 7 2024-08-31 310 August
- # 8 2024-09-30 330 September
- # 9 2024-10-31 340 October
- # 10 2024-11-30 360 November
- # 11 2024-12-31 380 December
-
- # 294-4、市场分析
- # date sales
- # mean median max
- # 0 April 270.0 270.0 270
- # 1 August 310.0 310.0 310
- # 2 December 380.0 380.0 380
- # 3 February 220.0 220.0 220
- # 4 January 200.0 200.0 200
- # 5 July 280.0 280.0 280
- # 6 June 320.0 320.0 320
- # 7 March 250.0 250.0 250
- # 8 May 300.0 300.0 300
- # 9 November 360.0 360.0 360
- # 10 October 340.0 340.0 340
- # 11 September 330.0 330.0 330
-
- # 294-5、客户和用户行为分析
- # month activity_count
- # 0 January 30
-
- # 294-6、财务和业务计划
- # month revenue
- # 0 April 1300
- # 1 August 1700
- # 2 December 2100
- # 3 February 1100
- # 4 January 1000
- # 5 July 1600
- # 6 June 1500
- # 7 March 1200
- # 8 May 1400
- # 9 November 2000
- # 10 October 1900
- # 11 September 1800

图2:
- # 295、pandas.Series.dt.day_name方法
- pandas.Series.dt.day_name(*args, **kwargs)
- Return the day names with specified locale.
-
- Parameters:
- locale
- str, optional
- Locale determining the language in which to return the day name. Default is English locale ('en_US.utf8'). Use the command locale -a on your terminal on Unix systems to find your locale language code.
-
- Returns:
- Series or Index
- Series or Index of day names.
295-2-1、*args(可选):其他位置参数,为后续扩展功能做预留。
295-2-2、**kwargs(可选):其他关键字参数,为后续扩展功能做预留。
295-2-2-1、locale(可选):指定返回的月份名称的语言环境。例如,“en”表示英语,“fr”表示法语。默认情况下,返回值是根据当前系统的默认语言环境生成的。
提取日期时间数据中的星期几名称。如,给定一个日期 2024-08-08,它会返回"Thursday"。
返回一个包含星期几名称的Series对象,字符串类型,例如"Monday"、"Tuesday"等。
使用场景:
295-5-1、数据分析:在进行时间序列分析时,提取星期几名称可以帮助识别数据的周期性模式。例如,销售数据可能在周末和工作日有不同的趋势。
295-5-2、可视化:当创建基于日期的图表时,使用星期几名称可以使图表更具可读性,便于观察不同星期几的表现。
295-5-3、报表生成:在生成日报或周报时,显示具体的星期几可以让读者更清晰地理解数据的上下文。
295-5-4、事件调度:在安排活动或任务时,了解每个日期是星期几可以帮助选择合适的时间。例如,某些活动可能更适合在周末进行。
295-5-5、数据清洗:在处理包含日期的原始数据时,可以通过提取星期几来过滤或标记特定日期的数据,以便后续分析。
295-5-6、用户行为分析:在分析用户行为时,了解用户在不同星期几的活动情况,可以帮助优化营销策略和产品推荐。
无
- # 295、pandas.Series.dt.day_name方法
- # 295-1、数据分析
- import pandas as pd
- # 创建示例销售数据
- data = {
- 'date': pd.date_range(start='2024-08-01', periods=10),
- 'sales': [200, 300, 250, 400, 500, 600, 700, 800, 900, 1000]
- }
- df = pd.DataFrame(data)
- # 提取星期几名称
- df['day_name'] = df['date'].dt.day_name()
- # 按星期几汇总销售数据
- sales_by_day = df.groupby('day_name')['sales'].sum().sort_index()
- print(sales_by_day, end='\n\n')
-
- # 295-2、可视化
- import matplotlib.pyplot as plt
- import pandas as pd
- # 创建示例销售数据
- data = {
- 'date': pd.date_range(start='2024-08-01', periods=10),
- 'sales': [200, 300, 250, 400, 500, 600, 700, 800, 900, 1000]
- }
- df = pd.DataFrame(data)
- # 提取星期几名称
- df['day_name'] = df['date'].dt.day_name()
- # 使用前面的数据
- sales_by_day = df.groupby('day_name')['sales'].sum().sort_index()
- # 绘制柱状图
- sales_by_day.plot(kind='bar',color='green')
- plt.title('Sales by Day of the Week')
- plt.xlabel('Day of the Week')
- plt.ylabel('Total Sales')
- plt.xticks(rotation=15, color='blue')
- plt.show()
-
- # 295-3、报表生成
- import pandas as pd
- # 创建示例销售数据
- data = {
- 'date': pd.date_range(start='2024-08-01', periods=10),
- 'sales': [200, 300, 250, 400, 500, 600, 700, 800, 900, 1000]
- }
- df = pd.DataFrame(data)
- # 创建日报
- report = df[['date', 'sales']]
- report['day_name'] = report['date'].dt.day_name()
- # 打印日报
- print(report, end='\n\n')
-
- # 295-4、事件调度
- import pandas as pd
- # 假设我们有一组活动数据
- events = {
- 'event': ['Event A', 'Event B', 'Event C', 'Event D'],
- 'date': pd.to_datetime(['2024-08-03', '2024-08-05', '2024-08-06', '2024-08-07'])
- }
- events_df = pd.DataFrame(events)
- # 添加星期几名称
- events_df['day_name'] = events_df['date'].dt.day_name()
- # 过滤出周末的活动
- weekend_events = events_df[events_df['day_name'].isin(['Saturday', 'Sunday'])]
- print(weekend_events, end='\n\n')
-
- # 295-5、数据清洗
- import pandas as pd
- # 假设我们有一组原始数据
- raw_data = {
- 'date': pd.date_range(start='2024-08-01', periods=10),
- 'value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- }
- raw_df = pd.DataFrame(raw_data)
- # 添加星期几名称
- raw_df['day_name'] = raw_df['date'].dt.day_name()
- # 添加一列标记周末
- raw_df['is_weekend'] = raw_df['day_name'].isin(['Saturday', 'Sunday'])
- print(raw_df, end='\n\n')
-
- # 295-6、用户行为分析
- import pandas as pd
- # 假设我们有用户行为数据
- user_activity = {
- 'user_id': [1, 1, 2, 2, 3, 3],
- 'activity_date': pd.to_datetime(['2024-08-01', '2024-08-02', '2024-08-03', '2024-08-04', '2024-08-05', '2024-08-06'])
- }
- activity_df = pd.DataFrame(user_activity)
- # 添加星期几名称
- activity_df['day_name'] = activity_df['activity_date'].dt.day_name()
- # 按星期几汇总用户活动
- activity_count = activity_df.groupby('day_name')['user_id'].count()
- print(activity_count)

- # 295、pandas.Series.dt.day_name方法
- # 295-1、数据分析
- # day_name
- # Friday 1200
- # Monday 500
- # Saturday 1250
- # Sunday 400
- # Thursday 1000
- # Tuesday 600
- # Wednesday 700
- # Name: sales, dtype: int64
-
- # 295-2、可视化
- # 见图3
-
- # 295-3、报表生成
- # date sales day_name
- # 0 2024-08-01 200 Thursday
- # 1 2024-08-02 300 Friday
- # 2 2024-08-03 250 Saturday
- # 3 2024-08-04 400 Sunday
- # 4 2024-08-05 500 Monday
- # 5 2024-08-06 600 Tuesday
- # 6 2024-08-07 700 Wednesday
- # 7 2024-08-08 800 Thursday
- # 8 2024-08-09 900 Friday
- # 9 2024-08-10 1000 Saturday
-
- # 295-4、事件调度
- # event date day_name
- # 0 Event A 2024-08-03 Saturday
-
- # 295-5、数据清洗
- # date value day_name is_weekend
- # 0 2024-08-01 1 Thursday False
- # 1 2024-08-02 2 Friday False
- # 2 2024-08-03 3 Saturday True
- # 3 2024-08-04 4 Sunday True
- # 4 2024-08-05 5 Monday False
- # 5 2024-08-06 6 Tuesday False
- # 6 2024-08-07 7 Wednesday False
- # 7 2024-08-08 8 Thursday False
- # 8 2024-08-09 9 Friday False
- # 9 2024-08-10 10 Saturday True
-
- # 295-6、用户行为分析
- # day_name
- # Friday 1
- # Monday 1
- # Saturday 1
- # Sunday 1
- # Thursday 1
- # Tuesday 1
- # Name: user_id, dtype: int64

图3:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。