当前位置:   article > 正文

Python酷库之旅-第三方库Pandas(072)

Python酷库之旅-第三方库Pandas(072)

目录

一、用法精讲

291、pandas.Series.dt.round函数

291-1、语法

291-2、参数

291-3、功能

291-4、返回值

291-5、说明

291-6、用法

291-6-1、数据准备

291-6-2、代码示例

291-6-3、结果输出

292、pandas.Series.dt.floor函数

292-1、语法

292-2、参数

292-3、功能

292-4、返回值

292-5、说明

292-6、用法

292-6-1、数据准备

292-6-2、代码示例

292-6-3、结果输出

293、pandas.Series.dt.ceil函数

293-1、语法

293-2、参数

293-3、功能

293-4、返回值

293-5、说明

293-6、用法

293-6-1、数据准备

293-6-2、代码示例

293-6-3、结果输出

294、pandas.Series.dt.month_name方法

294-1、语法

294-2、参数

294-3、功能

294-4、返回值

294-5、说明

294-6、用法

294-6-1、数据准备

294-6-2、代码示例

294-6-3、结果输出

295、pandas.Series.dt.day_name方法

295-1、语法

295-2、参数

295-3、功能

295-4、返回值

295-5、说明

295-6、用法

295-6-1、数据准备

295-6-2、代码示例

295-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

291、pandas.Series.dt.round函数
291-1、语法
  1. # 291、pandas.Series.dt.round函数
  2. pandas.Series.dt.round(*args, **kwargs)
  3. Perform round operation on the data to the specified freq.
  4. Parameters:
  5. freq
  6. str or Offset
  7. 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.
  8. ambiguous
  9. ‘infer’, bool-ndarray, ‘NaT’, default ‘raise
  10. Only relevant for DatetimeIndex:
  11. ‘infer’ will attempt to infer fall dst-transition hours based on order
  12. bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
  13. ‘NaT’ will return NaT where there are ambiguous times
  14. raise’ will raise an AmbiguousTimeError if there are ambiguous times.
  15. nonexistent
  16. ‘shift_forward’, ‘shift_backward’, ‘NaT’, timedelta, default ‘raise
  17. A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
  18. ‘shift_forward’ will shift the nonexistent time forward to the closest existing time
  19. ‘shift_backward’ will shift the nonexistent time backward to the closest existing time
  20. ‘NaT’ will return NaT where there are nonexistent times
  21. timedelta objects will shift nonexistent times by the timedelta
  22. raise’ will raise an NonExistentTimeError if there are nonexistent times.
  23. Returns:
  24. DatetimeIndex, TimedeltaIndex, or Series
  25. Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
  26. Raises:
  27. ValueError if the
  28. freq
  29. cannot be converted.
  30. Notes
  31. 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、参数

291-2-1、freq(必须)str or DateOffset,指定要四舍五入到的时间频率,常见的频率字符串包括:

  • s:
  • min:分钟
  • h:小时
  • D:
  • W:
  • M:
  • Q:季度
  • A:

291-2-2、ambiguous(可选,默认值为'raise')用于处理夏令时转换时的模棱两可的时间。默认情况下,如果时间不明确,会引发错误。可以选择以下选项之一:

  • 'raise':如果遇到不明确的时间,则引发错误。
  • 'NaT':将不明确的时间设置为NaT。
  • bool array:具有与时间戳相同长度的布尔数组,指示每个时间戳是否为夏令时。

291-2-3、nonexistent(可选,默认值为'raise')用于处理不存在的时间,例如从夏令时到标准时间的转换。默认情况下,如果时间不存在,会引发错误。可以选择以下选项之一:

  • 'raise':如果遇到不存在的时间,则引发错误。
  • 'NaT':将不存在的时间设置为NaT。
  • timedelta:使用给定的时间差调整不存在的时间。
291-3、功能

        用于将datetime数据四舍五入到最近的指定频率。例如,可以将datetime数据四舍五入到最近的秒、分钟、小时等,这对于需要标准化时间戳数据或进行时间间隔计算时非常有用。

291-4、返回值

        返回一个新的Series,其中包含四舍五入到指定频率的datetime数据。

291-5、说明

        使用场景:

291-5-1、数据标准化和对齐:在处理时间序列数据时,经常需要将时间戳对齐到统一的频率,以便进行进一步的分析和处理。例如,将不同时间戳对齐到最近的整点、整分或整秒,以便对不同时间序列进行比较或合并。

291-5-2、处理高频数据:在金融数据分析中,经常会处理高频交易数据,为了简化分析过程,可以将这些高频数据(如毫秒级别的交易数据)四舍五入到秒、分钟或小时级别,以便于观察趋势和模式。

291-5-3、生成时间窗口:在生成固定长度的时间窗口时,可以使用该方法将时间戳四舍五入到最近的窗口边界。例如,在生成按分钟分组的窗口时,可以将时间戳四舍五入到最近的分钟。

291-5-4、数据清理和预处理:在数据清理过程中,经常需要处理不精确的时间戳数据,通过将时间戳四舍五入到最近的标准时间,可以消除小的误差,使数据更加整洁和一致。

291-5-5、数据聚合:在对时间序列数据进行聚合操作(如计算平均值、总和等)之前,通常需要将时间戳对齐到同一频率。例如,在按小时聚合数据时,可以先将时间戳四舍五入到最近的小时。

291-6、用法
291-6-1、数据准备
291-6-2、代码示例
  1. # 291、pandas.Series.dt.round方法
  2. # 291-1、天气数据分析
  3. import pandas as pd
  4. # 创建示例天气数据
  5. weather_data = pd.DataFrame({
  6. 'timestamp': pd.to_datetime([
  7. '2024-08-07 14:35:29', '2024-08-07 14:35:45', '2024-08-07 14:36:12'
  8. ]),
  9. 'temperature': [25.3, 25.5, 25.7]
  10. })
  11. # 将时间戳四舍五入到最近的分钟
  12. weather_data['rounded_timestamp'] = weather_data['timestamp'].dt.round('min')
  13. # 按照四舍五入后的时间戳计算每分钟的平均温度
  14. average_temperature_per_minute = weather_data.groupby('rounded_timestamp')['temperature'].mean().reset_index()
  15. print("每分钟的平均温度:")
  16. print(average_temperature_per_minute, end='\n\n')
  17. # 291-2、交通流量分析
  18. import pandas as pd
  19. # 创建示例交通流量数据
  20. traffic_data = pd.DataFrame({
  21. 'timestamp': pd.to_datetime([
  22. '2024-08-07 08:15:12', '2024-08-07 08:16:45', '2024-08-07 08:17:59'
  23. ]),
  24. 'vehicle_count': [15, 20, 25]
  25. })
  26. # 将时间戳四舍五入到最近的小时
  27. traffic_data['rounded_timestamp'] = traffic_data['timestamp'].dt.round('h')
  28. # 按照四舍五入后的时间戳计算每小时的车流量总数
  29. vehicle_count_per_hour = traffic_data.groupby('rounded_timestamp')['vehicle_count'].sum().reset_index()
  30. print("每小时的车流量总数:")
  31. print(vehicle_count_per_hour, end='\n\n')
  32. # 291-3、股票交易数据分析
  33. import pandas as pd
  34. # 创建示例股票交易数据
  35. trade_data = pd.DataFrame({
  36. 'timestamp': pd.to_datetime([
  37. '2024-08-07 09:00:01.123', '2024-08-07 09:00:02.456', '2024-08-07 09:00:03.789'
  38. ]),
  39. 'trade_amount': [1000, 1500, 2000]
  40. })
  41. # 将时间戳四舍五入到最近的秒
  42. trade_data['rounded_timestamp'] = trade_data['timestamp'].dt.round('s')
  43. # 按照四舍五入后的时间戳计算每秒的交易总金额
  44. trade_amount_per_second = trade_data.groupby('rounded_timestamp')['trade_amount'].sum().reset_index()
  45. print("每秒的交易总金额:")
  46. print(trade_amount_per_second, end='\n\n')
  47. # 291-4、制造业生产数据分析
  48. import pandas as pd
  49. # 创建示例制造业生产数据
  50. production_data = pd.DataFrame({
  51. 'timestamp': pd.to_datetime([
  52. '2024-08-07 10:12:34', '2024-08-07 10:45:21', '2024-08-07 11:02:45'
  53. ]),
  54. 'quantity': [100, 200, 150]
  55. })
  56. # 将时间戳四舍五入到最近的小时
  57. production_data['rounded_timestamp'] = production_data['timestamp'].dt.round('h')
  58. # 按照四舍五入后的时间戳计算每小时的生产数量
  59. quantity_per_hour = production_data.groupby('rounded_timestamp')['quantity'].sum().reset_index()
  60. print("每小时的生产数量:")
  61. print(quantity_per_hour, end='\n\n')
  62. # 291-5、网站访问数据分析
  63. import pandas as pd
  64. # 创建示例网站访问数据
  65. visit_data = pd.DataFrame({
  66. 'timestamp': pd.to_datetime([
  67. '2024-08-07 15:03:45', '2024-08-07 15:04:15', '2024-08-07 15:04:35'
  68. ]),
  69. 'user_id': [101, 102, 103]
  70. })
  71. # 将时间戳四舍五入到最近的分钟
  72. visit_data['rounded_timestamp'] = visit_data['timestamp'].dt.round('min')
  73. # 按照四舍五入后的时间戳计算每分钟的访问量
  74. visit_count_per_minute = visit_data.groupby('rounded_timestamp')['user_id'].count().reset_index()
  75. print("每分钟的访问量:")
  76. print(visit_count_per_minute, end='\n\n')
  77. # 291-6、电力消耗数据分析
  78. import pandas as pd
  79. # 创建示例电力消耗数据
  80. power_consumption_data = pd.DataFrame({
  81. 'timestamp': pd.to_datetime([
  82. '2024-08-07 01:45:00', '2024-08-07 13:30:00', '2024-08-08 02:15:00'
  83. ]),
  84. 'power_consumption': [120, 150, 130]
  85. })
  86. # 将时间戳四舍五入到最近的一天
  87. power_consumption_data['rounded_timestamp'] = power_consumption_data['timestamp'].dt.round('D')
  88. # 按照四舍五入后的时间戳计算每天的电力消耗总量
  89. daily_power_consumption = power_consumption_data.groupby('rounded_timestamp')['power_consumption'].sum().reset_index()
  90. print("每天的电力消耗总量:")
  91. print(daily_power_consumption)
291-6-3、结果输出
  1. # 291、pandas.Series.dt.round方法
  2. # 291-1、天气数据分析
  3. # 每分钟的平均温度:
  4. # rounded_timestamp temperature
  5. # 0 2024-08-07 14:35:00 25.3
  6. # 1 2024-08-07 14:36:00 25.6
  7. # 291-2、交通流量分析
  8. # 每小时的车流量总数:
  9. # rounded_timestamp vehicle_count
  10. # 0 2024-08-07 08:00:00 60
  11. # 291-3、股票交易数据分析
  12. # 每秒的交易总金额:
  13. # rounded_timestamp trade_amount
  14. # 0 2024-08-07 09:00:01 1000
  15. # 1 2024-08-07 09:00:02 1500
  16. # 2 2024-08-07 09:00:04 2000
  17. # 291-4、制造业生产数据分析
  18. # 每小时的生产数量:
  19. # rounded_timestamp quantity
  20. # 0 2024-08-07 10:00:00 100
  21. # 1 2024-08-07 11:00:00 350
  22. # 291-5、网站访问数据分析
  23. # 每分钟的访问量:
  24. # rounded_timestamp user_id
  25. # 0 2024-08-07 15:04:00 2
  26. # 1 2024-08-07 15:05:00 1
  27. # 291-6、电力消耗数据分析
  28. # 每天的电力消耗总量:
  29. # rounded_timestamp power_consumption
  30. # 0 2024-08-07 120
  31. # 1 2024-08-08 280
292、pandas.Series.dt.floor函数
292-1、语法
  1. # 292、pandas.Series.dt.floor函数
  2. pandas.Series.dt.floor(*args, **kwargs)
  3. Perform floor operation on the data to the specified freq.
  4. Parameters:
  5. freq
  6. str or Offset
  7. 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.
  8. ambiguous
  9. ‘infer’, bool-ndarray, ‘NaT’, default ‘raise
  10. Only relevant for DatetimeIndex:
  11. ‘infer’ will attempt to infer fall dst-transition hours based on order
  12. bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
  13. ‘NaT’ will return NaT where there are ambiguous times
  14. raise’ will raise an AmbiguousTimeError if there are ambiguous times.
  15. nonexistent
  16. ‘shift_forward’, ‘shift_backward’, ‘NaT’, timedelta, default ‘raise
  17. A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
  18. ‘shift_forward’ will shift the nonexistent time forward to the closest existing time
  19. ‘shift_backward’ will shift the nonexistent time backward to the closest existing time
  20. ‘NaT’ will return NaT where there are nonexistent times
  21. timedelta objects will shift nonexistent times by the timedelta
  22. raise’ will raise an NonExistentTimeError if there are nonexistent times.
  23. Returns:
  24. DatetimeIndex, TimedeltaIndex, or Series
  25. Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
  26. Raises:
  27. ValueError if the
  28. freq
  29. cannot be converted.
  30. Notes
  31. 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、参数

292-2-1、freq(必须)str or DateOffset,指定要四舍五入到的时间频率,常见的频率字符串包括:

  • s:
  • min:分钟
  • h:小时
  • D:
  • W:
  • M:
  • Q:季度
  • A:

292-2-2、ambiguous(可选,默认值为'raise')用于处理夏令时转换时的模棱两可的时间。默认情况下,如果时间不明确,会引发错误。可以选择以下选项之一:

  • 'raise':如果遇到不明确的时间,则引发错误。
  • 'NaT':将不明确的时间设置为NaT。
  • bool array:具有与时间戳相同长度的布尔数组,指示每个时间戳是否为夏令时。

292-2-3、nonexistent(可选,默认值为'raise')用于处理不存在的时间,例如从夏令时到标准时间的转换。默认情况下,如果时间不存在,会引发错误。可以选择以下选项之一:

  • 'raise':如果遇到不存在的时间,则引发错误。
  • 'NaT':将不存在的时间设置为NaT。
  • timedelta:使用给定的时间差调整不存在的时间。
292-3、功能

        将每个时间戳向下取整到指定的时间频率。例如,如果我们有一系列时间戳,并希望将它们对齐到最近的小时,我们可以使用floor('h')。

292-4、返回值

        返回一个新的pandas.Series对象,其中的每个时间戳都被向下取整到指定频率,原始的Series对象不会被修改。

292-5、说明

        使用场景:

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-6、用法
292-6-1、数据准备
292-6-2、代码示例
  1. # 292、pandas.Series.dt.floor函数
  2. # 292-1、时间对齐
  3. import pandas as pd
  4. # 示例数据
  5. timestamps = pd.Series(pd.to_datetime(['2024-08-07 10:15:30', '2024-08-07 10:45:15', '2024-08-07 11:05:45']))
  6. floored_hours = timestamps.dt.floor('h')
  7. print(floored_hours, end='\n\n')
  8. # 292-2、数据聚合
  9. import pandas as pd
  10. # 示例数据
  11. data = {
  12. 'timestamp': pd.to_datetime(['2024-08-07 10:15:30', '2024-08-07 10:45:15', '2024-08-07 11:05:45']),
  13. 'value': [10, 20, 30]
  14. }
  15. df = pd.DataFrame(data)
  16. df['floored_hour'] = df['timestamp'].dt.floor('h')
  17. aggregated = df.groupby('floored_hour')['value'].sum()
  18. print(aggregated, end='\n\n')
  19. # 292-3、异常值处理
  20. import pandas as pd
  21. # 示例数据
  22. timestamps = pd.Series(pd.to_datetime(['2024-08-07 10:15:30', '2024-08-07 10:45:15', '2024-08-07 11:05:45']))
  23. floored_minutes = timestamps.dt.floor('min')
  24. print(floored_minutes, end='\n\n')
  25. # 292-4、缺失值填充
  26. import pandas as pd
  27. # 示例数据
  28. timestamps = pd.date_range('2024-08-07 10:00:00', periods=3, freq='h')
  29. values = [10, None, 30]
  30. df = pd.DataFrame({'timestamp': timestamps, 'value': values})
  31. df.set_index('timestamp', inplace=True)
  32. df = df.reindex(pd.date_range('2024-08-07 10:00:00', '2024-08-07 12:00:00', freq='h'))
  33. df['value'].fillna(method='ffill', inplace=True)
  34. print(df, end='\n\n')
  35. # 292-5、滚动窗口计算
  36. import pandas as pd
  37. # 示例数据
  38. 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']))
  39. floored_data = data.groupby(data.index.floor('h')).sum()
  40. rolling_mean = floored_data.rolling(window=2).mean()
  41. print(rolling_mean, end='\n\n')
  42. # 292-6、实时数据流处理
  43. import pandas as pd
  44. import numpy as np
  45. # 模拟实时数据流
  46. timestamps = pd.Series(pd.to_datetime(['2024-08-07 10:15:30', '2024-08-07 10:45:15', '2024-08-07 11:05:45']))
  47. values = pd.Series(np.random.randn(len(timestamps)))
  48. # 对齐到最近的分钟
  49. floored_minutes = timestamps.dt.floor('min')
  50. real_time_df = pd.DataFrame({'timestamp': floored_minutes, 'value': values})
  51. print(real_time_df)
292-6-3、结果输出
  1. # 292、pandas.Series.dt.floor函数
  2. # 292-1、时间对齐
  3. # 0 2024-08-07 10:00:00
  4. # 1 2024-08-07 10:00:00
  5. # 2 2024-08-07 11:00:00
  6. # dtype: datetime64[ns]
  7. # 292-2、数据聚合
  8. # floored_hour
  9. # 2024-08-07 10:00:00 30
  10. # 2024-08-07 11:00:00 30
  11. # Name: value, dtype: int64
  12. # 292-3、异常值处理
  13. # 0 2024-08-07 10:15:00
  14. # 1 2024-08-07 10:45:00
  15. # 2 2024-08-07 11:05:00
  16. # dtype: datetime64[ns]
  17. # 292-4、缺失值填充
  18. # value
  19. # 2024-08-07 10:00:00 10.0
  20. # 2024-08-07 11:00:00 10.0
  21. # 2024-08-07 12:00:00 30.0
  22. # 292-5、滚动窗口计算
  23. # 2024-08-07 10:00:00 NaN
  24. # 2024-08-07 11:00:00 30.0
  25. # dtype: float64
  26. # 292-6、实时数据流处理
  27. # timestamp value
  28. # 0 2024-08-07 10:15:00 -1.294484
  29. # 1 2024-08-07 10:45:00 -1.846297
  30. # 2 2024-08-07 11:05:00 -2.314171
293、pandas.Series.dt.ceil函数
293-1、语法
  1. # 293、pandas.Series.dt.ceil函数
  2. pandas.Series.dt.ceil(*args, **kwargs)
  3. Perform ceil operation on the data to the specified freq.
  4. Parameters:
  5. freq
  6. str or Offset
  7. 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.
  8. ambiguous
  9. ‘infer’, bool-ndarray, ‘NaT’, default ‘raise
  10. Only relevant for DatetimeIndex:
  11. ‘infer’ will attempt to infer fall dst-transition hours based on order
  12. bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
  13. ‘NaT’ will return NaT where there are ambiguous times
  14. raise’ will raise an AmbiguousTimeError if there are ambiguous times.
  15. nonexistent
  16. ‘shift_forward’, ‘shift_backward’, ‘NaT’, timedelta, default ‘raise
  17. A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
  18. ‘shift_forward’ will shift the nonexistent time forward to the closest existing time
  19. ‘shift_backward’ will shift the nonexistent time backward to the closest existing time
  20. ‘NaT’ will return NaT where there are nonexistent times
  21. timedelta objects will shift nonexistent times by the timedelta
  22. raise’ will raise an NonExistentTimeError if there are nonexistent times.
  23. Returns:
  24. DatetimeIndex, TimedeltaIndex, or Series
  25. Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
  26. Raises:
  27. ValueError if the
  28. freq
  29. cannot be converted.
  30. Notes
  31. 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、参数

293-2-1、freq(必须)str or DateOffset,指定要四舍五入到的时间频率,常见的频率字符串包括:

  • s:
  • min:分钟
  • h:小时
  • D:
  • W:
  • M:
  • Q:季度
  • A:

293-2-2、ambiguous(可选,默认值为'raise')用于处理夏令时转换时的模棱两可的时间。默认情况下,如果时间不明确,会引发错误。可以选择以下选项之一:

  • 'raise':如果遇到不明确的时间,则引发错误。
  • 'NaT':将不明确的时间设置为NaT。
  • bool array:具有与时间戳相同长度的布尔数组,指示每个时间戳是否为夏令时。

293-2-3、nonexistent(可选,默认值为'raise')用于处理不存在的时间,例如从夏令时到标准时间的转换。默认情况下,如果时间不存在,会引发错误。可以选择以下选项之一:

  • 'raise':如果遇到不存在的时间,则引发错误。
  • 'NaT':将不存在的时间设置为NaT。
  • timedelta:使用给定的时间差调整不存在的时间。
293-3、功能

        用于将时间序列中的每个时间戳向上取整到最近的指定频率。例如,如果将一个时间序列取整到小时,那么所有分钟和秒的信息都会被抹去,每个时间戳都会向上取整到下一个整点小时。

293-4、返回值

        返回值是一个pandas.Series对象,包含了将原时间序列的每个时间戳向上取整到最近频率的时间戳。

293-5、说明

        使用场景:

293-5-1、数据预处理:在处理时间序列数据时,有时候需要将时间戳标准化为相同的频率,以便进行后续分析。比如,将交易数据、传感器数据等按小时或天进行汇总分析。

293-5-2、时间间隔对齐:在计算时间间隔时,可能需要将时间戳向上取整到最近的频率,以确保时间间隔的一致性。例如,在计算每日、每小时的平均值、总和等统计数据时,可以使用该函数将时间戳对齐到整点。

293-5-3、可视化:在进行时间序列数据的可视化时,将时间戳向上取整到最近的频率可以使图表更易读。例如,将数据按小时或天进行聚合后再绘图,可以减少图表的复杂度,提高可读性。

293-5-4、数据合并:在合并多个时间序列数据时,可能需要将时间戳对齐到相同的频率,以便进行合并和比较。例如,将不同来源的传感器数据合并到同一个时间轴上,可以使用该函数将所有时间戳对齐到最近的整点。

293-6、用法
293-6-1、数据准备
293-6-2、代码示例
  1. # 293、pandas.Series.dt.ceil函数
  2. # 293-1、数据预处理
  3. import pandas as pd
  4. # 示例数据:传感器数据
  5. data = {
  6. 'timestamp': [
  7. '2024-08-07 08:45:00', '2024-08-07 08:50:00', '2024-08-07 09:05:00',
  8. '2024-08-07 09:15:00', '2024-08-07 10:05:00'
  9. ],
  10. 'value': [10, 12, 13, 15, 20]
  11. }
  12. df = pd.DataFrame(data)
  13. df['timestamp'] = pd.to_datetime(df['timestamp'])
  14. # 将时间戳向上取整到最近的小时
  15. df['rounded_timestamp'] = df['timestamp'].dt.ceil('h')
  16. # 按小时汇总数据
  17. hourly_summary = df.groupby('rounded_timestamp')['value'].sum().reset_index()
  18. print(hourly_summary, end='\n\n')
  19. # 293-2、时间间隔对齐
  20. import pandas as pd
  21. # 示例数据:交易数据
  22. trade_data = {
  23. 'trade_time': [
  24. '2024-08-07 10:15:25', '2024-08-07 10:15:35', '2024-08-07 10:15:45',
  25. '2024-08-07 10:16:00', '2024-08-07 10:16:20'
  26. ],
  27. 'price': [100, 101, 102, 103, 104]
  28. }
  29. trade_df = pd.DataFrame(trade_data)
  30. trade_df['trade_time'] = pd.to_datetime(trade_df['trade_time'])
  31. # 将时间戳向上取整到最近的分钟
  32. trade_df['aligned_time'] = trade_df['trade_time'].dt.ceil('min')
  33. print(trade_df, end='\n\n')
  34. # 293-3、可视化
  35. import matplotlib.pyplot as plt
  36. # 示例数据:网页访问数据
  37. visit_data = {
  38. 'visit_time': [
  39. '2024-08-01 12:34:56', '2024-08-01 14:22:33', '2024-08-02 09:18:45',
  40. '2024-08-02 10:12:34', '2024-08-03 16:45:12'
  41. ],
  42. 'visits': [1, 1, 1, 1, 1]
  43. }
  44. visit_df = pd.DataFrame(visit_data)
  45. visit_df['visit_time'] = pd.to_datetime(visit_df['visit_time'])
  46. # 将时间戳向上取整到最近的天
  47. visit_df['day'] = visit_df['visit_time'].dt.ceil('D')
  48. # 按天汇总数据
  49. daily_visits = visit_df.groupby('day')['visits'].sum().reset_index()
  50. # 可视化
  51. plt.figure(figsize=(10, 5))
  52. plt.plot(daily_visits['day'], daily_visits['visits'], marker='o')
  53. plt.xlabel('Date')
  54. plt.ylabel('Number of Visits')
  55. plt.title('Daily Web Visits')
  56. plt.grid(True)
  57. plt.show()
  58. # 293-4、数据合并
  59. import pandas as pd
  60. # 示例数据:传感器A数据
  61. sensor_a_data = {
  62. 'timestamp': [
  63. '2024-08-07 10:15:25', '2024-08-07 10:35:12', '2024-08-07 10:55:45'
  64. ],
  65. 'sensor_a_value': [0.1, 0.3, 0.5]
  66. }
  67. sensor_a_df = pd.DataFrame(sensor_a_data)
  68. sensor_a_df['timestamp'] = pd.to_datetime(sensor_a_df['timestamp'])
  69. sensor_a_df['timestamp'] = sensor_a_df['timestamp'].dt.ceil('h')
  70. # 示例数据:传感器B数据
  71. sensor_b_data = {
  72. 'timestamp': [
  73. '2024-08-07 11:05:21', '2024-08-07 11:22:33'
  74. ],
  75. 'sensor_b_value': [0.6, 0.7]
  76. }
  77. sensor_b_df = pd.DataFrame(sensor_b_data)
  78. sensor_b_df['timestamp'] = pd.to_datetime(sensor_b_df['timestamp'])
  79. sensor_b_df['timestamp'] = sensor_b_df['timestamp'].dt.ceil('h')
  80. # 合并数据
  81. merged_df = pd.merge(sensor_a_df, sensor_b_df, on='timestamp', how='outer')
  82. print(merged_df, end='\n\n')
293-6-3、结果输出
  1. # 293、pandas.Series.dt.ceil函数
  2. # 293-1、数据预处理
  3. # rounded_timestamp value
  4. # 0 2024-08-07 09:00:00 22
  5. # 1 2024-08-07 10:00:00 28
  6. # 2 2024-08-07 11:00:00 20
  7. # 293-2、时间间隔对齐
  8. # trade_time price aligned_time
  9. # 0 2024-08-07 10:15:25 100 2024-08-07 10:16:00
  10. # 1 2024-08-07 10:15:35 101 2024-08-07 10:16:00
  11. # 2 2024-08-07 10:15:45 102 2024-08-07 10:16:00
  12. # 3 2024-08-07 10:16:00 103 2024-08-07 10:16:00
  13. # 4 2024-08-07 10:16:20 104 2024-08-07 10:17:00
  14. # 293-3、可视化
  15. # 见图1
  16. # 293-4、数据合并
  17. # timestamp sensor_a_value sensor_b_value
  18. # 0 2024-08-07 11:00:00 0.1 NaN
  19. # 1 2024-08-07 11:00:00 0.3 NaN
  20. # 2 2024-08-07 11:00:00 0.5 NaN
  21. # 3 2024-08-07 12:00:00 NaN 0.6
  22. # 4 2024-08-07 12:00:00 NaN 0.7

图1:

294、pandas.Series.dt.month_name方法
294-1、语法
  1. # 294、pandas.Series.dt.month_name方法
  2. pandas.Series.dt.month_name(*args, **kwargs)
  3. Return the month names with specified locale.
  4. Parameters:
  5. locale
  6. str, optional
  7. 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.
  8. Returns:
  9. Series or Index
  10. Series or Index of month names.
294-2、参数

294-2-1、*args(可选)其他位置参数,为后续扩展功能做预留。

294-2-2、**kwargs(可选)其他关键字参数,为后续扩展功能做预留。

294-2-2-1、locale(可选)指定返回的月份名称的语言环境。例如,“en”表示英语,“fr”表示法语。默认情况下,返回值是根据当前系统的默认语言环境生成的。

294-3、功能

        用于返回datetime类型的Series对象中每个日期的月份名称,且这些名称是以字符串的形式返回的,例如“January”、“February”等。

294-4、返回值

        返回一个pandas.Series对象,其中包含每个日期的月份名称。

294-5、说明

        使用场景:

294-5-1、数据可视化:在绘制时间序列图或统计图时,可以使用月份名称来标签和分类数据,使图表更具可读性。例如,绘制每个月的销售额图表时,使用月份名称作为 x 轴标签。

294-5-2、报告和分析:在生成数据报告时,可能需要按月份分组数据。将日期转换为月份名称可以帮助更直观地展示每个月的数据汇总和趋势。

294-5-3、数据清洗和预处理:在数据清洗过程中,可能需要将时间戳数据转换为更易于分析的格式,将日期转换为月份名称可以帮助将数据按月份进行聚合或分析。

294-5-4、市场分析:对于销售数据、用户活动数据等,可以按月份进行分析,以识别季节性趋势、销售高峰期或用户行为模式。

294-5-5、客户和用户行为分析:分析客户行为时,月份名称可以帮助识别客户在不同月份的活动模式或趋势,进而调整营销策略或活动计划。

294-5-6、财务和业务计划:企业在进行财务分析和业务计划时,需要按月份跟踪和预测各种财务指标,如收入、支出和利润等。

294-6、用法
294-6-1、数据准备
294-6-2、代码示例
  1. # 294、pandas.Series.dt.month_name方法
  2. # 294-1、数据可视化
  3. import matplotlib.pyplot as plt
  4. import pandas as pd
  5. # 创建示例数据
  6. data = {
  7. 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
  8. 'sales': [200, 220, 250, 270, 300, 320, 280, 310, 330, 340, 360, 380]
  9. }
  10. df = pd.DataFrame(data)
  11. # 添加月份名称列
  12. df['month'] = df['date'].dt.month_name()
  13. # 绘制图表
  14. plt.figure(figsize=(10, 6))
  15. plt.plot(df['month'], df['sales'], marker='o', color='purple')
  16. plt.xlabel('Month')
  17. plt.ylabel('Sales')
  18. plt.title('Monthly Sales')
  19. plt.xticks(rotation=45)
  20. plt.grid(True)
  21. # 添加数据标签
  22. for i, value in enumerate(df['sales']):
  23. plt.text(i, value + 5, str(value), ha='center', va='bottom', color='red', fontweight='bold') # 在每个点上方显示标签并加粗
  24. plt.show()
  25. # 294-2、报告和分析
  26. import pandas as pd
  27. # 创建示例数据
  28. data = {
  29. 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
  30. 'sales': [200, 220, 250, 270, 300, 320, 280, 310, 330, 340, 360, 380]
  31. }
  32. df = pd.DataFrame(data)
  33. monthly_sales = df.groupby(df['date'].dt.month_name())['sales'].sum().reset_index()
  34. monthly_sales.columns = ['Month', 'Total Sales']
  35. print(monthly_sales, end='\n\n')
  36. # 294-3、数据清洗和预处理
  37. import pandas as pd
  38. # 创建示例数据
  39. data = {
  40. 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
  41. 'sales': [200, 220, 250, 270, 300, 320, 280, 310, 330, 340, 360, 380]
  42. }
  43. df = pd.DataFrame(data)
  44. df['month_name'] = df['date'].dt.month_name()
  45. print(df, end='\n\n')
  46. # 294-4、市场分析
  47. import pandas as pd
  48. # 创建示例数据
  49. data = {
  50. 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
  51. 'sales': [200, 220, 250, 270, 300, 320, 280, 310, 330, 340, 360, 380]
  52. }
  53. df = pd.DataFrame(data)
  54. monthly_summary = df.groupby(df['date'].dt.month_name()).agg({
  55. 'sales': ['mean', 'median', 'max']
  56. }).reset_index()
  57. print(monthly_summary, end='\n\n')
  58. # 294-5、客户和用户行为分析
  59. import pandas as pd
  60. # 示例数据
  61. user_data = {
  62. 'activity_date': pd.date_range(start='2024-01-01', periods=30, freq='D'),
  63. 'user_id': range(1, 31)
  64. }
  65. user_df = pd.DataFrame(user_data)
  66. # 添加月份名称列
  67. user_df['month'] = user_df['activity_date'].dt.month_name()
  68. # 按月份统计用户活动次数
  69. activity_summary = user_df.groupby('month').size().reset_index(name='activity_count')
  70. print(activity_summary, end='\n\n')
  71. # 294-6、财务和业务计划
  72. import pandas as pd
  73. # 示例财务数据
  74. financial_data = {
  75. 'date': pd.date_range(start='2024-01-01', periods=12, freq='ME'),
  76. 'revenue': [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100]
  77. }
  78. financial_df = pd.DataFrame(financial_data)
  79. # 添加月份名称列
  80. financial_df['month'] = financial_df['date'].dt.month_name()
  81. # 按月份汇总收入
  82. monthly_revenue = financial_df.groupby('month')['revenue'].sum().reset_index()
  83. print(monthly_revenue)
294-6-3、结果输出
  1. # 294、pandas.Series.dt.month_name方法
  2. # 294-1、数据可视化
  3. # 见图2
  4. # 294-2、报告和分析
  5. # Month Total Sales
  6. # 0 April 270
  7. # 1 August 310
  8. # 2 December 380
  9. # 3 February 220
  10. # 4 January 200
  11. # 5 July 280
  12. # 6 June 320
  13. # 7 March 250
  14. # 8 May 300
  15. # 9 November 360
  16. # 10 October 340
  17. # 11 September 330
  18. # 294-3、数据清洗和预处理
  19. # date sales month_name
  20. # 0 2024-01-31 200 January
  21. # 1 2024-02-29 220 February
  22. # 2 2024-03-31 250 March
  23. # 3 2024-04-30 270 April
  24. # 4 2024-05-31 300 May
  25. # 5 2024-06-30 320 June
  26. # 6 2024-07-31 280 July
  27. # 7 2024-08-31 310 August
  28. # 8 2024-09-30 330 September
  29. # 9 2024-10-31 340 October
  30. # 10 2024-11-30 360 November
  31. # 11 2024-12-31 380 December
  32. # 294-4、市场分析
  33. # date sales
  34. # mean median max
  35. # 0 April 270.0 270.0 270
  36. # 1 August 310.0 310.0 310
  37. # 2 December 380.0 380.0 380
  38. # 3 February 220.0 220.0 220
  39. # 4 January 200.0 200.0 200
  40. # 5 July 280.0 280.0 280
  41. # 6 June 320.0 320.0 320
  42. # 7 March 250.0 250.0 250
  43. # 8 May 300.0 300.0 300
  44. # 9 November 360.0 360.0 360
  45. # 10 October 340.0 340.0 340
  46. # 11 September 330.0 330.0 330
  47. # 294-5、客户和用户行为分析
  48. # month activity_count
  49. # 0 January 30
  50. # 294-6、财务和业务计划
  51. # month revenue
  52. # 0 April 1300
  53. # 1 August 1700
  54. # 2 December 2100
  55. # 3 February 1100
  56. # 4 January 1000
  57. # 5 July 1600
  58. # 6 June 1500
  59. # 7 March 1200
  60. # 8 May 1400
  61. # 9 November 2000
  62. # 10 October 1900
  63. # 11 September 1800

图2:

 

295、pandas.Series.dt.day_name方法
295-1、语法
  1. # 295、pandas.Series.dt.day_name方法
  2. pandas.Series.dt.day_name(*args, **kwargs)
  3. Return the day names with specified locale.
  4. Parameters:
  5. locale
  6. str, optional
  7. 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.
  8. Returns:
  9. Series or Index
  10. Series or Index of day names.
295-2、参数

295-2-1、*args(可选)其他位置参数,为后续扩展功能做预留。

295-2-2、**kwargs(可选)其他关键字参数,为后续扩展功能做预留。

295-2-2-1、locale(可选)指定返回的月份名称的语言环境。例如,“en”表示英语,“fr”表示法语。默认情况下,返回值是根据当前系统的默认语言环境生成的。

295-3、功能

        提取日期时间数据中的星期几名称。如,给定一个日期 2024-08-08,它会返回"Thursday"。

295-4、返回值

        返回一个包含星期几名称的Series对象,字符串类型,例如"Monday"、"Tuesday"等。

295-5、说明

        使用场景:

295-5-1、数据分析:在进行时间序列分析时,提取星期几名称可以帮助识别数据的周期性模式。例如,销售数据可能在周末和工作日有不同的趋势。

295-5-2、可视化:当创建基于日期的图表时,使用星期几名称可以使图表更具可读性,便于观察不同星期几的表现。

295-5-3、报表生成:在生成日报或周报时,显示具体的星期几可以让读者更清晰地理解数据的上下文。

295-5-4、事件调度:在安排活动或任务时,了解每个日期是星期几可以帮助选择合适的时间。例如,某些活动可能更适合在周末进行。

295-5-5、数据清洗:在处理包含日期的原始数据时,可以通过提取星期几来过滤或标记特定日期的数据,以便后续分析。

295-5-6、用户行为分析:在分析用户行为时,了解用户在不同星期几的活动情况,可以帮助优化营销策略和产品推荐。

295-6、用法
295-6-1、数据准备
295-6-2、代码示例
  1. # 295、pandas.Series.dt.day_name方法
  2. # 295-1、数据分析
  3. import pandas as pd
  4. # 创建示例销售数据
  5. data = {
  6. 'date': pd.date_range(start='2024-08-01', periods=10),
  7. 'sales': [200, 300, 250, 400, 500, 600, 700, 800, 900, 1000]
  8. }
  9. df = pd.DataFrame(data)
  10. # 提取星期几名称
  11. df['day_name'] = df['date'].dt.day_name()
  12. # 按星期几汇总销售数据
  13. sales_by_day = df.groupby('day_name')['sales'].sum().sort_index()
  14. print(sales_by_day, end='\n\n')
  15. # 295-2、可视化
  16. import matplotlib.pyplot as plt
  17. import pandas as pd
  18. # 创建示例销售数据
  19. data = {
  20. 'date': pd.date_range(start='2024-08-01', periods=10),
  21. 'sales': [200, 300, 250, 400, 500, 600, 700, 800, 900, 1000]
  22. }
  23. df = pd.DataFrame(data)
  24. # 提取星期几名称
  25. df['day_name'] = df['date'].dt.day_name()
  26. # 使用前面的数据
  27. sales_by_day = df.groupby('day_name')['sales'].sum().sort_index()
  28. # 绘制柱状图
  29. sales_by_day.plot(kind='bar',color='green')
  30. plt.title('Sales by Day of the Week')
  31. plt.xlabel('Day of the Week')
  32. plt.ylabel('Total Sales')
  33. plt.xticks(rotation=15, color='blue')
  34. plt.show()
  35. # 295-3、报表生成
  36. import pandas as pd
  37. # 创建示例销售数据
  38. data = {
  39. 'date': pd.date_range(start='2024-08-01', periods=10),
  40. 'sales': [200, 300, 250, 400, 500, 600, 700, 800, 900, 1000]
  41. }
  42. df = pd.DataFrame(data)
  43. # 创建日报
  44. report = df[['date', 'sales']]
  45. report['day_name'] = report['date'].dt.day_name()
  46. # 打印日报
  47. print(report, end='\n\n')
  48. # 295-4、事件调度
  49. import pandas as pd
  50. # 假设我们有一组活动数据
  51. events = {
  52. 'event': ['Event A', 'Event B', 'Event C', 'Event D'],
  53. 'date': pd.to_datetime(['2024-08-03', '2024-08-05', '2024-08-06', '2024-08-07'])
  54. }
  55. events_df = pd.DataFrame(events)
  56. # 添加星期几名称
  57. events_df['day_name'] = events_df['date'].dt.day_name()
  58. # 过滤出周末的活动
  59. weekend_events = events_df[events_df['day_name'].isin(['Saturday', 'Sunday'])]
  60. print(weekend_events, end='\n\n')
  61. # 295-5、数据清洗
  62. import pandas as pd
  63. # 假设我们有一组原始数据
  64. raw_data = {
  65. 'date': pd.date_range(start='2024-08-01', periods=10),
  66. 'value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  67. }
  68. raw_df = pd.DataFrame(raw_data)
  69. # 添加星期几名称
  70. raw_df['day_name'] = raw_df['date'].dt.day_name()
  71. # 添加一列标记周末
  72. raw_df['is_weekend'] = raw_df['day_name'].isin(['Saturday', 'Sunday'])
  73. print(raw_df, end='\n\n')
  74. # 295-6、用户行为分析
  75. import pandas as pd
  76. # 假设我们有用户行为数据
  77. user_activity = {
  78. 'user_id': [1, 1, 2, 2, 3, 3],
  79. 'activity_date': pd.to_datetime(['2024-08-01', '2024-08-02', '2024-08-03', '2024-08-04', '2024-08-05', '2024-08-06'])
  80. }
  81. activity_df = pd.DataFrame(user_activity)
  82. # 添加星期几名称
  83. activity_df['day_name'] = activity_df['activity_date'].dt.day_name()
  84. # 按星期几汇总用户活动
  85. activity_count = activity_df.groupby('day_name')['user_id'].count()
  86. print(activity_count)
295-6-3、结果输出
  1. # 295、pandas.Series.dt.day_name方法
  2. # 295-1、数据分析
  3. # day_name
  4. # Friday 1200
  5. # Monday 500
  6. # Saturday 1250
  7. # Sunday 400
  8. # Thursday 1000
  9. # Tuesday 600
  10. # Wednesday 700
  11. # Name: sales, dtype: int64
  12. # 295-2、可视化
  13. # 见图3
  14. # 295-3、报表生成
  15. # date sales day_name
  16. # 0 2024-08-01 200 Thursday
  17. # 1 2024-08-02 300 Friday
  18. # 2 2024-08-03 250 Saturday
  19. # 3 2024-08-04 400 Sunday
  20. # 4 2024-08-05 500 Monday
  21. # 5 2024-08-06 600 Tuesday
  22. # 6 2024-08-07 700 Wednesday
  23. # 7 2024-08-08 800 Thursday
  24. # 8 2024-08-09 900 Friday
  25. # 9 2024-08-10 1000 Saturday
  26. # 295-4、事件调度
  27. # event date day_name
  28. # 0 Event A 2024-08-03 Saturday
  29. # 295-5、数据清洗
  30. # date value day_name is_weekend
  31. # 0 2024-08-01 1 Thursday False
  32. # 1 2024-08-02 2 Friday False
  33. # 2 2024-08-03 3 Saturday True
  34. # 3 2024-08-04 4 Sunday True
  35. # 4 2024-08-05 5 Monday False
  36. # 5 2024-08-06 6 Tuesday False
  37. # 6 2024-08-07 7 Wednesday False
  38. # 7 2024-08-08 8 Thursday False
  39. # 8 2024-08-09 9 Friday False
  40. # 9 2024-08-10 10 Saturday True
  41. # 295-6、用户行为分析
  42. # day_name
  43. # Friday 1
  44. # Monday 1
  45. # Saturday 1
  46. # Sunday 1
  47. # Thursday 1
  48. # Tuesday 1
  49. # Name: user_id, dtype: int64

图3:

 

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/957626
推荐阅读
相关标签
  

闽ICP备14008679号