当前位置:   article > 正文

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

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

目录

一、用法精讲

251、pandas.Series.tz_localize方法

251-1、语法

251-2、参数

251-3、功能

251-4、返回值

251-5、说明

251-6、用法

251-6-1、数据准备

251-6-2、代码示例

251-6-3、结果输出

252、pandas.Series.at_time方法

252-1、语法

252-2、参数

252-3、功能

252-4、返回值

252-5、说明

252-6、用法

252-6-1、数据准备

252-6-2、代码示例

252-6-3、结果输出

253、pandas.Series.between_time方法

253-1、语法

253-2、参数

253-3、功能

253-4、返回值

253-5、说明

253-6、用法

253-6-1、数据准备

253-6-2、代码示例

253-6-3、结果输出

254、pandas.Series.str方法

254-1、语法

254-2、参数

254-3、功能

254-3-1、转换大小写

254-3-2、字符串匹配和搜索

254-3-3、字符串替换和去除

254-3-4、字符串分割和连接

254-3-5、提取和访问子串

254-3-6、格式化和填充

254-3-7、长度和计数

254-4、返回值

254-5、说明

254-6、用法

254-6-1、数据准备

254-6-2、代码示例

254-6-3、结果输出

255、pandas.Series.cat方法

255-1、语法

255-2、参数

255-3、功能

255-4、返回值

255-5、说明

255-6、用法

255-6-1、数据准备

255-6-2、代码示例

255-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

251、pandas.Series.tz_localize方法
251-1、语法
  1. # 251、pandas.Series.tz_localize方法
  2. pandas.Series.tz_localize(tz, axis=0, level=None, copy=None, ambiguous='raise', nonexistent='raise')
  3. Localize tz-naive index of a Series or DataFrame to target time zone.
  4. This operation localizes the Index. To localize the values in a timezone-naive Series, use Series.dt.tz_localize().
  5. Parameters:
  6. tzstr or tzinfo or None
  7. Time zone to localize. Passing None will remove the time zone information and preserve local time.
  8. axis{0 or ‘index’, 1 or ‘columns’}, default 0
  9. The axis to localize
  10. levelint, str, default None
  11. If axis ia a MultiIndex, localize a specific level. Otherwise must be None.
  12. copybool, default True
  13. Also make a copy of the underlying data.
  14. Note
  15. The copy keyword will change behavior in pandas 3.0. Copy-on-Write will be enabled by default, which means that all methods with a copy keyword will use a lazy copy mechanism to defer the copy and ignore the copy keyword. The copy keyword will be removed in a future version of pandas.
  16. You can already get the future behavior and improvements through enabling copy on write pd.options.mode.copy_on_write = True
  17. ambiguous‘infer’, bool-ndarray, ‘NaT’, default ‘raise
  18. When clocks moved backward due to DST, ambiguous times may arise. For example in Central European Time (UTC+01), when going from 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the ambiguous parameter dictates how ambiguous times should be handled.
  19. ‘infer’ will attempt to infer fall dst-transition hours based on order
  20. bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
  21. ‘NaT’ will return NaT where there are ambiguous times
  22. raise’ will raise an AmbiguousTimeError if there are ambiguous times.
  23. nonexistentstr, default ‘raise
  24. A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST. Valid values are:
  25. ‘shift_forward’ will shift the nonexistent time forward to the closest existing time
  26. ‘shift_backward’ will shift the nonexistent time backward to the closest existing time
  27. ‘NaT’ will return NaT where there are nonexistent times
  28. timedelta objects will shift nonexistent times by the timedelta
  29. raise’ will raise an NonExistentTimeError if there are nonexistent times.
  30. Returns:
  31. Series/DataFrame
  32. Same type as the input.
  33. Raises:
  34. TypeError
  35. If the TimeSeries is tz-aware and tz is not None.
251-2、参数

251-2-1、tz(必须)字符串或pytz.timezone对象,指定要本地化的时区,可以是时区的名称(如'US/Eastern')或一个pytz时区对象。

251-2-2、axis(可选,默认值为0)整数或字符串,指定沿着哪个轴进行本地化,对于Series,这个参数通常被忽略,因为Series只有一个轴,即轴0。

251-2-3、level(可选,默认值为None)整数或字符串,当处理多级索引(MultiIndex)时,此参数指定要本地化的级别,对普通的Series对象通常不需要使用。

251-2-4、copy(可选,默认值为None)布尔值,如果设置为False,会尝试在原地修改Series;如果为True,则会返回一个新的Series;默认值为None时,会自动选择合适的策略。

251-2-5、ambiguous(可选,默认值为'raise')字符串,处理夏令时切换期间的模糊时间,如果设置为'raise',则在出现模糊时间时抛出异常;如果设置为'NaT',则将这些时间标记为NaT(Not a Time);如果设置为'ignore',则保持原样。

251-2-6、nonexistent(可选,默认值为'raise')字符串,处理由于时区转换而不存在的时间,如果设置为'raise',则在出现不存在的时间时抛出异常;如果设置为'NaT',则将这些时间标记为NaT(Not a Time);如果设置为'shift',则将这些时间移到最近的存在时间。

251-3、功能

        用于将一个没有时区的Series对象的时间戳本地化到指定的时区。

251-4、返回值

        返回一个新的Series对象,其中时间戳已经被本地化到指定的时区,如果copy=False,可能会修改原始Series对象(具体取决于是否需要复制),新Series的时间戳将带有时区信息,格式为DatetimeIndex。

251-5、说明

        无

251-6、用法
251-6-1、数据准备
251-6-2、代码示例
  1. # 251、pandas.Series.tz_localize方法
  2. import pandas as pd
  3. s = pd.Series(range(7),
  4. index=pd.DatetimeIndex(['2024-8-2 01:30:00',
  5. '2024-8-2 02:00:00',
  6. '2024-8-2 02:30:00',
  7. '2024-8-2 03:00:00',
  8. '2024-8-2 03:30:00',
  9. '2024-8-2 04:00:00',
  10. '2024-8-2 04:30:00']))
  11. data = s.tz_localize('CET', ambiguous='infer')
  12. print(data)
251-6-3、结果输出
  1. # 251、pandas.Series.tz_localize方法
  2. # 2024-08-02 01:30:00+02:00 0
  3. # 2024-08-02 02:00:00+02:00 1
  4. # 2024-08-02 02:30:00+02:00 2
  5. # 2024-08-02 03:00:00+02:00 3
  6. # 2024-08-02 03:30:00+02:00 4
  7. # 2024-08-02 04:00:00+02:00 5
  8. # 2024-08-02 04:30:00+02:00 6
  9. # dtype: int64
252、pandas.Series.at_time方法
252-1、语法
  1. # 252、pandas.Series.at_time方法
  2. pandas.Series.at_time(time, asof=False, axis=None)
  3. Select values at particular time of day (e.g., 9:30AM).
  4. Parameters:
  5. time
  6. datetime.time or str
  7. The values to select.
  8. axis
  9. {0 or ‘index’, 1 or ‘columns’}, default 0
  10. For Series this parameter is unused and defaults to 0.
  11. Returns:
  12. Series or DataFrame
  13. Raises:
  14. TypeError
  15. If the index is not a DatetimeIndex
252-2、参数

252-2-1、time(必须)字符串或datetime.time,指定要提取的时间,这个时间应当是datetime.time对象或符合时间格式的字符串(如'06:18')。

252-2-2、asof(可选,默认值为False)布尔值,如果设置为True,方法将返回在指定时间点之前最近的时间;如果为False,则方法仅返回与指定时间完全匹配的时间点的数据。

252-2-3、axis(可选,默认值为None)整数或字符串,指定沿着哪个轴进行操作,在Series中,通常可以忽略这个参数,因为Series只有一个轴(即轴0)。

252-3、功能

        用于从Series中筛选出指定时间点的数据,该方法将时间与Series的索引进行匹配,提取出符合指定时间的数据行,可以用来获取一天中某个特定时间点的数据,忽略具体的日期信息。

252-4、返回值

        返回一个新的Series对象,其中包含了在指定时间点的数据,返回的Series中的索引是与指定时间匹配的时间戳。

252-5、说明

        无

252-6、用法
252-6-1、数据准备
252-6-2、代码示例
  1. # 252、pandas.Series.at_time方法
  2. import pandas as pd
  3. # 创建一个时间序列
  4. idx = pd.date_range('2024-01-01', periods=4, freq='h')
  5. data = pd.Series([1, 2, 3, 4], index=idx)
  6. # 提取每天的'02:00'数据
  7. result = data.at_time('02:00')
  8. print("提取的时间点数据:")
  9. print(result)
252-6-3、结果输出
  1. # 252、pandas.Series.at_time方法
  2. # 提取的时间点数据:
  3. # 2024-01-01 02:00:00 3
  4. # Freq: h, dtype: int64
253、pandas.Series.between_time方法
253-1、语法
  1. # 253、pandas.Series.between_time方法
  2. pandas.Series.between_time(start_time, end_time, inclusive='both', axis=None)
  3. Select values between particular times of the day (e.g., 9:00-9:30 AM).
  4. By setting start_time to be later than end_time, you can get the times that are not between the two times.
  5. Parameters:
  6. start_time
  7. datetime.time or str
  8. Initial time as a time filter limit.
  9. end_time
  10. datetime.time or str
  11. End time as a time filter limit.
  12. inclusive
  13. {“both”, “neither”, “left”, “right”}, default “both”
  14. Include boundaries; whether to set each bound as closed or open.
  15. axis
  16. {0 or ‘index’, 1 or ‘columns’}, default 0
  17. Determine range time on index or columns value. For Series this parameter is unused and defaults to 0.
  18. Returns:
  19. Series or DataFrame
  20. Data from the original object filtered to the specified dates range.
  21. Raises:
  22. TypeError
  23. If the index is not a DatetimeIndex
253-2、参数

253-2-1、start_time(必须)字符串或datetime.time,指定时间范围的开始时间,应当是datetime.time对象或符合时间格式的字符串(如'06:18')。

253-2-2、end_time(必须)字符串或datetime.time,指定时间范围的结束时间,应当是datetime.time对象或符合时间格式的字符串(如'17:30')。

253-2-3、inclusive(可选,默认值为'both'){'both','neither','left','right'},指定时间范围的边界条件,可以选择以下四个值:

  • 'both':包括开始时间和结束时间。
  • 'neither':不包括开始时间和结束时间。
  • 'left':包括开始时间,但不包括结束时间。
  • 'right':不包括开始时间,但包括结束时间。

253-2-4、axis(可选,默认值为None)整数或字符串,指定沿着哪个轴进行操作,在Series中,通常可以忽略这个参数,因为Series只有一个轴(即轴0)。

253-3、功能

        用于从Series中筛选出在指定时间范围内的数据,它将时间与Series的索引进行匹配,提取出在开始时间和结束时间之间的数据,该方法可以用来获取一天中某个时间段的数据,忽略日期信息。

253-4、返回值

        返回一个新的Series对象,其中包含了在指定时间范围内的数据,返回的Series中的索引是与指定时间范围匹配的时间戳。

253-5、说明

        无

253-6、用法
253-6-1、数据准备
253-6-2、代码示例
  1. # 253、pandas.Series.between_time方法
  2. import pandas as pd
  3. # 创建一个时间序列
  4. idx = pd.date_range('2024-08-01', periods=24, freq='h')
  5. data = pd.Series(range(24), index=idx)
  6. # 提取每天的'09:00'到'17:00'之间的数据
  7. result = data.between_time('09:00', '17:00')
  8. print("提取的时间范围数据:")
  9. print(result)
253-6-3、结果输出
  1. # 253、pandas.Series.between_time方法
  2. # 提取的时间范围数据:
  3. # 2024-08-01 09:00:00 9
  4. # 2024-08-01 10:00:00 10
  5. # 2024-08-01 11:00:00 11
  6. # 2024-08-01 12:00:00 12
  7. # 2024-08-01 13:00:00 13
  8. # 2024-08-01 14:00:00 14
  9. # 2024-08-01 15:00:00 15
  10. # 2024-08-01 16:00:00 16
  11. # 2024-08-01 17:00:00 17
  12. # Freq: h, dtype: int64
254、pandas.Series.str方法
254-1、语法
  1. # 254、pandas.Series.str方法
  2. pandas.Series.str()
  3. Vectorized string functions for Series and Index.
  4. NAs stay NA unless handled otherwise by a particular method. Patterned after Python’s string methods, with some inspiration from R’s stringr package.
254-2、参数

        无

254-3、功能
254-3-1、转换大小写

254-3-1-1、str.lower()将每个字符串转换为小写。

254-3-1-2、str.upper():将每个字符串转换为大写。

254-3-2、字符串匹配和搜索

254-3-2-1、str.contains(pattern)检查每个字符串是否包含指定的模式,返回布尔值的 Series。

254-3-2-2、str.startswith(prefix)检查每个字符串是否以指定的前缀开头,返回布尔值的 Series。

254-3-2-3、str.endswith(suffix)检查每个字符串是否以指定的后缀结尾,返回布尔值的 Series。

254-3-3、字符串替换和去除

254-3-3-1、str.replace(old,new)将每个字符串中的指定内容替换为新的内容。

254-3-3-2、str.strip()去除每个字符串的前后空白字符。

254-3-4、字符串分割和连接

254-3-4-1、str.split(separator)按照指定分隔符将字符串分割为列表。

254-3-4-2、str.join(sep)使用指定的分隔符连接列表中的元素。

254-3-5、提取和访问子串

254-3-5-1、str.extract(pattern)使用正则表达式提取匹配的子字符串。

254-3-5-2、str.get(i)获取每个字符串的第i个字符。

254-3-6、格式化和填充

254-3-6-1、str.pad(width,side='left',fillchar='')使用指定字符填充字符串,使其达到指定宽度。可以选择在左、右或两侧填充。

254-3-6-2、str.zfill(width)在左侧填充零,使字符串达到指定宽度。

254-3-7、长度和计数

254-3-7-1、str.len()返回每个字符串的长度。

254-3-7-2、str.count(pattern)计算每个字符串中匹配模式的出现次数。

254-4、返回值

        功能不同,产生了不同的返回值。

254-5、说明

        无

254-6、用法
254-6-1、数据准备
254-6-2、代码示例
  1. # 254、pandas.Series.str方法
  2. # 254-1、转换大小写
  3. # 254-1-1、str.lower():将每个字符串转换为小写
  4. import pandas as pd
  5. s = pd.Series(['Hello', 'World', 'Pandas'])
  6. s_lower = s.str.lower()
  7. print(s_lower, end='\n\n')
  8. # 254-1-2、str.upper():将每个字符串转换为大写
  9. import pandas as pd
  10. s = pd.Series(['Hello', 'World', 'Pandas'])
  11. s_upper = s.str.upper()
  12. print(s_upper, end='\n\n')
  13. # 254-2、字符串匹配和搜索
  14. # 254-2-1、str.contains(pattern):检查每个字符串是否包含指定的模式,返回布尔值的Series
  15. import pandas as pd
  16. s = pd.Series(['Hello', 'World', 'Pandas'])
  17. s_contains = s.str.contains('o')
  18. print(s_contains, end='\n\n')
  19. # 254-2-2、str.startswith(prefix):检查每个字符串是否以指定的前缀开头,返回布尔值的Series
  20. import pandas as pd
  21. s = pd.Series(['Hello', 'World', 'Pandas'])
  22. s_startswith = s.str.startswith('P')
  23. print(s_startswith, end='\n\n')
  24. # 254-2-3、str.endswith(suffix):检查每个字符串是否以指定的后缀结尾,返回布尔值的Series
  25. import pandas as pd
  26. s = pd.Series(['Hello', 'World', 'Pandas'])
  27. s_endswith = s.str.endswith('s')
  28. print(s_endswith, end='\n\n')
  29. # 254-3、字符串替换和去除
  30. # 254-3-1、str.replace(old, new):将每个字符串中的指定内容替换为新的内容
  31. import pandas as pd
  32. s = pd.Series(['Hello', 'World', 'Pandas'])
  33. s_replace = s.str.replace('o', '0')
  34. print(s_replace, end='\n\n')
  35. # 254-3-2、str.strip():去除每个字符串的前后空白字符
  36. import pandas as pd
  37. s_with_spaces = pd.Series([' Hello ', ' World ', ' Pandas '])
  38. s_strip = s_with_spaces.str.strip()
  39. print(s_strip, end='\n\n')
  40. # 254-4、字符串分割和连接
  41. # 254-4-1、str.split(separator):按照指定分隔符将字符串分割为列表
  42. import pandas as pd
  43. s = pd.Series(['Hello', 'World', 'Pandas'])
  44. s_split = s.str.split('l')
  45. print(s_split, end='\n\n')
  46. # 254-4-2、str.join(sep):使用指定的分隔符连接列表中的元素
  47. import pandas as pd
  48. s_join = pd.Series([['a', 'b', 'c'], ['d', 'e'], ['f']])
  49. s_joined = s_join.str.join('-')
  50. print(s_joined, end='\n\n')
  51. # 254-5、提取和访问子串
  52. # 254-5-1、str.extract(pattern):使用正则表达式提取匹配的子字符串
  53. import pandas as pd
  54. s_dates = pd.Series(['2022-08-01', '2023-07-06', '2024-08-03'])
  55. s_extract = s_dates.str.extract(r'(\d{4})-(\d{2})-(\d{2})')
  56. print(s_extract, end='\n\n')
  57. # 254-5-2、str.get(i):获取每个字符串的第i个字符
  58. import pandas as pd
  59. s = pd.Series(['Hello', 'World', 'Pandas'])
  60. s_get = s.str.get(1)
  61. print(s_get, end='\n\n')
  62. # 254-6、格式化和填充
  63. # 254-6-1、str.pad(width, side='left', fillchar=' '):使用指定字符填充字符串,使其达到指定宽度。可以选择在左、右或两侧填充
  64. import pandas as pd
  65. s = pd.Series(['Hello', 'World', 'Pandas'])
  66. s_pad = s.str.pad(10, side='right', fillchar='*')
  67. print(s_pad, end='\n\n')
  68. # 254-6-2、str.zfill(width):在左侧填充零,使字符串达到指定宽度
  69. import pandas as pd
  70. s = pd.Series(['Hello', 'World', 'Pandas'])
  71. s_zfill = s.str.zfill(10)
  72. print(s_zfill, end='\n\n')
  73. # 254-7、长度和计数
  74. # 254-7-1、str.len():返回每个字符串的长度
  75. import pandas as pd
  76. s = pd.Series(['Hello', 'World', 'Pandas'])
  77. s_len = s.str.len()
  78. print(s_len, end='\n\n')
  79. # 254-7-2、str.count(pattern):计算每个字符串中匹配模式的出现次数
  80. import pandas as pd
  81. s = pd.Series(['Hello', 'World', 'Pandas'])
  82. s_count = s.str.count('l')
  83. print(s_count, end='\n\n')
  84. # 254-8、综合案例
  85. import pandas as pd
  86. # 创建一个包含混合文本数据的Series
  87. data = pd.Series([' Myelsa ', 'bob123', 'C@r0l', 'DAVID'])
  88. # 清洗和标准化文本数据
  89. cleaned_data = data.str.strip().str.lower().str.replace(r'\d+', '').str.replace(r'[^a-z]', '')
  90. print(cleaned_data)
254-6-3、结果输出
  1. # 254、pandas.Series.str方法
  2. # 254-1、转换大小写
  3. # 254-1-1、str.lower():将每个字符串转换为小写
  4. # 0 hello
  5. # 1 world
  6. # 2 pandas
  7. # dtype: object
  8. # 254-1-2、str.upper():将每个字符串转换为大写
  9. # 0 HELLO
  10. # 1 WORLD
  11. # 2 PANDAS
  12. # dtype: object
  13. # 254-2、字符串匹配和搜索
  14. # 254-2-1、str.contains(pattern):检查每个字符串是否包含指定的模式,返回布尔值的Series
  15. # 0 True
  16. # 1 True
  17. # 2 False
  18. # dtype: bool
  19. # 254-2-2、str.startswith(prefix):检查每个字符串是否以指定的前缀开头,返回布尔值的Series
  20. # 0 False
  21. # 1 False
  22. # 2 True
  23. # dtype: bool
  24. # 254-2-3、str.endswith(suffix):检查每个字符串是否以指定的后缀结尾,返回布尔值的Series
  25. # 0 False
  26. # 1 False
  27. # 2 True
  28. # dtype: bool
  29. # 254-3、字符串替换和去除
  30. # 254-3-1、str.replace(old, new):将每个字符串中的指定内容替换为新的内容
  31. # 0 Hell0
  32. # 1 W0rld
  33. # 2 Pandas
  34. # dtype: object
  35. # 254-3-2、str.strip():去除每个字符串的前后空白字符
  36. # 0 Hello
  37. # 1 World
  38. # 2 Pandas
  39. # dtype: object
  40. # 254-4、字符串分割和连接
  41. # 254-4-1、str.split(separator):按照指定分隔符将字符串分割为列表
  42. # 0 [He, , o]
  43. # 1 [Wor, d]
  44. # 2 [Pandas]
  45. # dtype: object
  46. # 254-4-2、str.join(sep):使用指定的分隔符连接列表中的元素
  47. # 0 a-b-c
  48. # 1 d-e
  49. # 2 f
  50. # dtype: object
  51. # 254-5、提取和访问子串
  52. # 254-5-1、str.extract(pattern):
  53. # 0 1 2
  54. # 0 2022 08 01
  55. # 1 2023 07 06
  56. # 2 2024 08 03
  57. # 254-5-2、str.get(i):获取每个字符串的第i个字符
  58. # 0 e
  59. # 1 o
  60. # 2 a
  61. # dtype: object
  62. # 254-6、格式化和填充
  63. # 254-6-1、str.pad(width, side='left', fillchar=' '):使用指定字符填充字符串,使其达到指定宽度。可以选择在左、右或两侧填充
  64. # 0 Hello*****
  65. # 1 World*****
  66. # 2 Pandas****
  67. # dtype: object
  68. # 254-6-2、str.zfill(width):在左侧填充零,使字符串达到指定宽度
  69. # 0 00000Hello
  70. # 1 00000World
  71. # 2 0000Pandas
  72. # dtype: object
  73. # 254-7、长度和计数
  74. # 254-7-1、str.len():返回每个字符串的长度
  75. # 0 5
  76. # 1 5
  77. # 2 6
  78. # dtype: int64
  79. # 254-7-2、str.count(pattern):计算每个字符串中匹配模式的出现次数
  80. # 0 2
  81. # 1 1
  82. # 2 0
  83. # dtype: int64
  84. # 254-8、综合案例
  85. # 0 myelsa
  86. # 1 bob123
  87. # 2 c@r0l
  88. # 3 david
  89. # dtype: object
255、pandas.Series.cat方法
255-1、语法
  1. # 255、pandas.Series.cat方法
  2. pandas.Series.cat()
  3. Accessor object for categorical properties of the Series values.
  4. Parameters:
  5. data
  6. Series or CategoricalIndex
255-2、参数

        无

255-3、功能

        提供了对类别数据的创建、修改、重命名和管理等功能,使得处理数据时可以利用类别数据的特性进行更加细致的操作和分析。

255-4、返回值

        返回值是一个Categorical对象,它提供了关于类别数据的详细信息,包括类别的列表、类别的顺序(如果有的话)等,该对象使得对类别数据的进一步操作和分析更加灵活和高效。

255-5、说明

        无

255-6、用法
255-6-1、数据准备
255-6-2、代码示例
  1. # 255、pandas.Series.cat方法
  2. import pandas as pd
  3. # 创建一个包含类别数据的 Series
  4. data = pd.Series(['apple', 'banana', 'apple', 'orange', 'banana'], dtype='category')
  5. # 输出原始数据及其类别
  6. print("Original Series:")
  7. print(data)
  8. print("Categories:")
  9. print(data.cat.categories, end='\n\n')
  10. # 255-1、设置类别的顺序
  11. data = data.cat.set_categories(['banana', 'apple', 'orange'], ordered=True)
  12. print("Ordered Categories:")
  13. print(data.cat.categories, end='\n\n')
  14. # 255-2、 添加新类别
  15. data = data.cat.add_categories(['grape'])
  16. print("Categories after Adding 'grape':")
  17. print(data.cat.categories, end='\n\n')
  18. # 255-3、 删除类别
  19. data = data.cat.remove_categories(['orange'])
  20. print("Categories after Removing 'orange':")
  21. print(data.cat.categories, end='\n\n')
  22. # 255-4、 重命名类别
  23. data = data.cat.rename_categories({'banana': 'yellow_banana', 'apple': 'green_apple'})
  24. print("Categories after Renaming:")
  25. print(data.cat.categories, end='\n\n')
  26. # 255-5、 获取类别的整数编码
  27. print("Integer Encoding of the Series:")
  28. print(data.cat.codes, end='\n\n')
  29. # 255-6、查看数据和类别编码
  30. print("Data with Integer Encoding:")
  31. print(data)
255-6-3、结果输出
  1. # 255、pandas.Series.cat方法
  2. # Original Series:
  3. # 0 apple
  4. # 1 banana
  5. # 2 apple
  6. # 3 orange
  7. # 4 banana
  8. # dtype: category
  9. # Categories (3, object): ['apple', 'banana', 'orange']
  10. # Categories:
  11. # Index(['apple', 'banana', 'orange'], dtype='object')
  12. # 255-1、设置类别的顺序
  13. # Ordered Categories:
  14. # Index(['banana', 'apple', 'orange'], dtype='object')
  15. # 255-2、 添加新类别
  16. # Categories after Adding 'grape':
  17. # Index(['banana', 'apple', 'orange', 'grape'], dtype='object')
  18. # 255-3、 删除类别
  19. # Categories after Removing 'orange':
  20. # Index(['banana', 'apple', 'grape'], dtype='object')
  21. # 255-4、 重命名类别
  22. # Categories after Renaming:
  23. # Index(['yellow_banana', 'green_apple', 'grape'], dtype='object')
  24. # 255-5、 获取类别的整数编码
  25. # Integer Encoding of the Series:
  26. # 0 1
  27. # 1 0
  28. # 2 1
  29. # 3 -1
  30. # 4 0
  31. # dtype: int8
  32. # 255-6、查看数据和类别编码
  33. # Data with Integer Encoding:
  34. # 0 green_apple
  35. # 1 yellow_banana
  36. # 2 green_apple
  37. # 3 NaN
  38. # 4 yellow_banana
  39. # dtype: category
  40. # Categories (3, object): ['yellow_banana' < 'green_apple' < 'grape']

二、推荐阅读

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

闽ICP备14008679号