当前位置:   article > 正文

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

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

目录

一、用法精讲

236、pandas.Series.explode方法

236-1、语法

236-2、参数

236-3、功能

236-4、返回值

236-5、说明

236-6、用法

236-6-1、数据准备

236-6-2、代码示例

236-6-3、结果输出

237、pandas.Series.searchsorted方法

237-1、语法

237-2、参数

237-3、功能

237-4、返回值

237-5、说明

237-6、用法

237-6-1、数据准备

237-6-2、代码示例

237-6-3、结果输出

238、pandas.Series.ravel方法

238-1、语法

238-2、参数

238-3、功能

238-4、返回值

238-5、说明

238-6、用法

238-6-1、数据准备

238-6-2、代码示例

238-6-3、结果输出

239、pandas.Series.repeat方法

239-1、语法

239-2、参数

239-3、功能

239-4、返回值

239-5、说明

239-6、用法

239-6-1、数据准备

239-6-2、代码示例

239-6-3、结果输出

240、pandas.Series.squeeze方法

240-1、语法

240-2、参数

240-3、功能

240-4、返回值

240-5、说明

240-6、用法

240-6-1、数据准备

240-6-2、代码示例

240-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

236、pandas.Series.explode方法
236-1、语法
  1. # 236、pandas.Series.explode方法
  2. pandas.Series.explode(ignore_index=False)
  3. Transform each element of a list-like to a row.
  4. Parameters:
  5. ignore_index
  6. bool, default False
  7. If True, the resulting index will be labeled 0, 1, …, n - 1.
  8. Returns:
  9. Series
  10. Exploded lists to rows; index will be duplicated for these rows.
236-2、参数

236-2-1、ignore_index(可选,默认值为False)布尔值,若设置为False,则保持原始索引,展开后的新Series保持原始Series的索引;若设置为True,则忽略原始索引,展开后的新Series使用新的整数索引。

236-3、功能

        将包含列表、元组或类似的可迭代对象的Series进行展开,使每个元素在新Series中都有一行。简单来说,它可以将一个包含列表的Series转换为一个平坦的Series,其中每个列表元素占据一行。

236-4、返回值

        返回一个新的Series,其索引可能是原来的索引(如果ignore_index=False)或者是重新生成的整数索引(如果ignore_index=True)每个列表-like 元素中的项都变成新的行,如果某元素不是列表-like,则保持不变。

236-5、说明

        使用场景:

236-5-1、处理嵌套列表数据:在处理从JSON、数据库或其他数据源导入的嵌套数据时,常常会遇到列表嵌套在单个单元格中的情况。explode()方法可以将这些嵌套列表展开为单独的行,便于进一步分析。如:电商订单数据,每个订单包含多个商品。

236-5-2、数据清洗与预处理:在数据清洗过程中,常常需要将一个单元格中的多个值分成多行,以便进行进一步的操作和清洗。如:用户标签数据,每个用户可能有多个标签。

236-5-3、文本分析:在自然语言处理和文本分析中,常常需要将文本数据拆分成单词或短语,然后对这些拆分后的单词或短语进行分析,explode()方法可以帮助将分词后的列表展开为单独的行。如:分词后的文本数据。

236-5-4、时间序列数据处理:在时间序列数据处理中,可能会有某些时间点对应多个事件或值的情况,explode()方法可以将这些多值的时间点展开为多个时间点,以便于进一步分析和处理。如:某时间点的多个事件。

236-6、用法
236-6-1、数据准备
236-6-2、代码示例
  1. # 236、pandas.Series.explode方法
  2. # 236-1、处理嵌套列表数据
  3. import pandas as pd
  4. # 示例数据
  5. orders = pd.Series([['item1', 'item2'], ['item3'], ['item4', 'item5', 'item6']])
  6. # 使用explode方法展开商品列表
  7. exploded_orders = orders.explode()
  8. print(exploded_orders, end='\n\n')
  9. # 236-2、数据清洗与预处理
  10. import pandas as pd
  11. # 示例数据
  12. user_tags = pd.Series([['tag1', 'tag2'], ['tag3'], ['tag4', 'tag5', 'tag6']])
  13. # 使用explode方法展开标签列表
  14. exploded_tags = user_tags.explode()
  15. print(exploded_tags, end='\n\n')
  16. # 236-3、文本分析
  17. import pandas as pd
  18. # 示例数据
  19. texts = pd.Series([['word1', 'word2', 'word3'], ['word4'], ['word5', 'word6']])
  20. # 使用explode方法展开分词后的列表
  21. exploded_texts = texts.explode()
  22. print(exploded_texts, end='\n\n')
  23. # 236-4、时间序列数据处理
  24. import pandas as pd
  25. # 示例数据
  26. time_series = pd.Series([['event1', 'event2'], ['event3'], ['event4', 'event5', 'event6']])
  27. # 使用explode方法展开时间点的事件列表
  28. exploded_time_series = time_series.explode()
  29. print(exploded_time_series)
236-6-3、结果输出
  1. # 236、pandas.Series.explode方法
  2. # 236-1、处理嵌套列表数据
  3. # 0 item1
  4. # 0 item2
  5. # 1 item3
  6. # 2 item4
  7. # 2 item5
  8. # 2 item6
  9. # dtype: object
  10. # 236-2、数据清洗与预处理
  11. # 0 tag1
  12. # 0 tag2
  13. # 1 tag3
  14. # 2 tag4
  15. # 2 tag5
  16. # 2 tag6
  17. # dtype: object
  18. # 236-3、文本分析
  19. # 0 word1
  20. # 0 word2
  21. # 0 word3
  22. # 1 word4
  23. # 2 word5
  24. # 2 word6
  25. # dtype: object
  26. # 236-4、时间序列数据处理
  27. # 0 event1
  28. # 0 event2
  29. # 1 event3
  30. # 2 event4
  31. # 2 event5
  32. # 2 event6
  33. # dtype: object
237、pandas.Series.searchsorted方法
237-1、语法
  1. # 237、pandas.Series.searchsorted方法
  2. pandas.Series.searchsorted(value, side='left', sorter=None)
  3. Find indices where elements should be inserted to maintain order.
  4. Find the indices into a sorted Series self such that, if the corresponding elements in value were inserted before the indices, the order of self would be preserved.
  5. Note
  6. The Series must be monotonically sorted, otherwise wrong locations will likely be returned. Pandas does not check this for you.
  7. Parameters:
  8. value
  9. array-like or scalar
  10. Values to insert into self.
  11. side
  12. {‘left’, ‘right’}, optional
  13. If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of self).
  14. sorter
  15. 1-D array-like, optional
  16. Optional array of integer indices that sort self into ascending order. They are typically the result of np.argsort.
  17. Returns:
  18. int or array of int
  19. A scalar or array of insertion points with the same shape as value.
237-2、参数

237-2-1、value(必须)标量或数组型数据,表示要查找的值。

237-2-2、side(可选,默认值为'left'){'left', 'right'},表示在找到等于value的元素时,是插入到左边还是右边。'left'表示插入到等于value的元素的左侧,'right'表示插入到右侧。

237-2-3、sorter(可选,默认值为None)可选数组型数据,表示Series排序后的索引。

237-3、功能

        用于查找一个值或一组值在一个排序好的Series中应插入的位置,以保持顺序不变,该方法对于二分查找、数据插入和位置索引等操作非常有用。

237-4、返回值

        返回整数或整数数组,表示插入位置的索引。

237-5、说明

        无

237-6、用法
237-6-1、数据准备
237-6-2、代码示例
  1. # 237、pandas.Series.searchsorted方法
  2. # 237-1、基本用法
  3. import pandas as pd
  4. # 创建一个排序好的Series
  5. s = pd.Series([1, 2, 3, 4, 5])
  6. # 查找插入值的位置
  7. index = s.searchsorted(3)
  8. print(index, end='\n\n')
  9. # 237-2、使用'side'参数
  10. import pandas as pd
  11. # 创建一个排序好的Series
  12. s = pd.Series([1, 2, 3, 3, 4, 5])
  13. # 查找插入值的位置(插入左侧)
  14. index_left = s.searchsorted(3, side='left')
  15. print(index_left)
  16. # 查找插入值的位置(插入右侧)
  17. index_right = s.searchsorted(3, side='right')
  18. print(index_right, end='\n\n')
  19. # 237-3、处理未排序的Series
  20. import pandas as pd
  21. # 创建一个未排序的Series
  22. s = pd.Series([5, 1, 4, 2, 3])
  23. # 获取排序后的索引
  24. sorter = s.argsort()
  25. # 查找插入值的位置
  26. index = s.searchsorted(3, sorter=sorter)
  27. print(index)
237-6-3、结果输出
  1. # 237、pandas.Series.searchsorted方法
  2. # 237-1、基本用法
  3. # 2
  4. # 237-2、使用'side'参数
  5. # 2
  6. # 4
  7. # 237-3、处理未排序的Series
  8. # 2
238、pandas.Series.ravel方法
238-1、语法
  1. # 238、pandas.Series.ravel方法
  2. pandas.Series.ravel(order='C')
  3. Return the flattened underlying data as an ndarray or ExtensionArray.
  4. Deprecated since version 2.2.0: Series.ravel is deprecated. The underlying array is already 1D, so ravel is not necessary. Use to_numpy() for conversion to a numpy array instead.
  5. Returns:
  6. numpy.ndarray or ExtensionArray
  7. Flattened data of the Series.
238-2、参数

238-2-1、order(可选,默认值为'C')字符串类型,选项有:

  • 'C':按照C语言的行优先顺序(行优先,即先按行读取再按列读取)展平数组。
  • 'F':按照Fortran语言的列优先顺序(列优先,即先按列读取再按行读取)展平数组。
  • 'A':如果原始数据在内存中是按行优先顺序存储的,则返回按行优先顺序展平的数组;如果原始数据在内存中是按列优先顺序存储的,则返回按列优先顺序展平的数组。
  • 'K':尽可能保持原始数据的存储顺序。
238-3、功能

        用于将Series对象展平为一个一维的NumPy数组。

238-4、返回值

        返回一个一维的NumPy数组,其中包含了原Series对象中的所有数据。

238-5、说明

        此方法目前版本仍然能用,但后续将被pandas.Series.to_numpy方法替代。

238-6、用法
238-6-1、数据准备
238-6-2、代码示例
  1. # 238、pandas.Series.ravel方法
  2. import pandas as pd
  3. import numpy as np
  4. # 创建一个Pandas Series对象
  5. data = pd.Series([1, 2, 3, 4, 5])
  6. # 使用ravel()方法
  7. flattened_data_C = data.ravel(order='C')
  8. flattened_data_F = data.ravel(order='F')
  9. print("Flattened data (C order):", flattened_data_C)
  10. print("Flattened data (F order):", flattened_data_F)
238-6-3、结果输出
  1. # 238、pandas.Series.ravel方法
  2. # Flattened data (C order): [1 2 3 4 5]
  3. # Flattened data (F order): [1 2 3 4 5]
239、pandas.Series.repeat方法
239-1、语法
  1. # 239、pandas.Series.repeat方法
  2. pandas.Series.repeat(repeats, axis=None)
  3. Repeat elements of a Series.
  4. Returns a new Series where each element of the current Series is repeated consecutively a given number of times.
  5. Parameters:
  6. repeats
  7. int or array of ints
  8. The number of repetitions for each element. This should be a non-negative integer. Repeating 0 times will return an empty Series.
  9. axis
  10. None
  11. Unused. Parameter needed for compatibility with DataFrame.
  12. Returns:
  13. Series
  14. Newly created Series with repeated elements.
239-2、参数

239-2-1、repeats(必须)整数或整数数组,如果是单个整数,则Series中的每个元素都会被重复该整数指定的次数;如果是一个与Series等长的整数数组,则每个元素会按照对应位置的整数进行重复。

239-2-2、axis(可选,默认值为None)参数在Series中无效,因为Series是一维的,因此这个参数在这里不被使用。

239-3、功能

        用于将Series中的每个元素按指定的次数重复,该方法对于数据扩展或增加数据量非常有用。

239-4、返回值

        返回一个新的Pandas Series对象,其中每个元素按指定的次数进行了重复。

239-5、说明

        无

239-6、用法
239-6-1、数据准备
239-6-2、代码示例
  1. # 239、pandas.Series.repeat方法
  2. import pandas as pd
  3. # 创建一个Pandas Series对象
  4. data = pd.Series([1, 2, 3])
  5. # 每个元素重复3次
  6. repeated_data_1 = data.repeat(3)
  7. # 每个元素根据给定的数组分别重复
  8. repeated_data_2 = data.repeat([1, 2, 3])
  9. print("Repeated data (3 times):")
  10. print(repeated_data_1)
  11. print("\nRepeated data (1, 2, 3 times respectively):")
  12. print(repeated_data_2)
239-6-3、结果输出
  1. # 239、pandas.Series.repeat方法
  2. # Repeated data (3 times):
  3. # 0 1
  4. # 0 1
  5. # 0 1
  6. # 1 2
  7. # 1 2
  8. # 1 2
  9. # 2 3
  10. # 2 3
  11. # 2 3
  12. # dtype: int64
  13. #
  14. # Repeated data (1, 2, 3 times respectively):
  15. # 0 1
  16. # 1 2
  17. # 1 2
  18. # 2 3
  19. # 2 3
  20. # 2 3
  21. # dtype: int64
240、pandas.Series.squeeze方法
240-1、语法
  1. # 240、pandas.Series.squeeze方法
  2. pandas.Series.squeeze(axis=None)
  3. Squeeze 1 dimensional axis objects into scalars.
  4. Series or DataFrames with a single element are squeezed to a scalar. DataFrames with a single column or a single row are squeezed to a Series. Otherwise the object is unchanged.
  5. This method is most useful when you don’t know if your object is a Series or DataFrame, but you do know it has just a single column. In that case you can safely call squeeze to ensure you have a Series.
  6. Parameters:
  7. axis
  8. {0 or ‘index’, 1 or ‘columns’, None}, default None
  9. A specific axis to squeeze. By default, all length-1 axes are squeezed. For Series this parameter is unused and defaults to None.
  10. Returns:
  11. DataFrame, Series, or scalar
  12. The projection after squeezing axis or all the axes.
240-2、参数

240-2-1、axis(可选,默认值为None){None, 0, 1},选项有:

  • None:默认值,自动删除长度为1的维度。
  • 0或index:如果Series或DataFrame在索引轴上只有一个值,则压缩该维度。
  • 1或columns:如果Series或DataFrame在列轴上只有一个值,则压缩该维度。
240-3、功能

        用于去除Series中长度为1的维度,它常用于处理从DataFrame中提取的单列或单行结果,使得返回的结果更加简洁。

240-4、返回值

        返回一个去除了长度为1的维度后的对象,如果没有长度为1的维度,则返回原对象。

240-5、说明

        无

240-6、用法
240-6-1、数据准备
240-6-2、代码示例
  1. # 240、pandas.Series.squeeze方法
  2. # 240-1、从DataFrame提取单行或单列
  3. import pandas as pd
  4. # 创建一个DataFrame
  5. df = pd.DataFrame({
  6. 'A': [10, 20, 30],
  7. 'B': [15, 25, 35]
  8. })
  9. # 提取单列
  10. single_column = df[['A']]
  11. squeezed_column = single_column.squeeze()
  12. # 提取单行
  13. single_row = df.iloc[[0]]
  14. squeezed_row = single_row.squeeze()
  15. print("Original single column DataFrame:")
  16. print(single_column)
  17. print("Squeezed Series from single column:")
  18. print(squeezed_column)
  19. print("Original single row DataFrame:")
  20. print(single_row)
  21. print("Squeezed Series from single row:")
  22. print(squeezed_row, end='\n\n')
  23. # 240-2、数据分组后的操作
  24. import pandas as pd
  25. # 创建一个DataFrame
  26. df = pd.DataFrame({
  27. 'Category': ['A', 'A', 'B'],
  28. 'Value': [10, 20, 30]
  29. })
  30. # 按'Category'分组并计算均值
  31. grouped = df.groupby('Category').mean()
  32. # 获取特定类别的数据并使用squeeze
  33. single_category_mean = grouped.loc[['A']]
  34. squeezed_category_mean = single_category_mean.squeeze()
  35. print("Grouped mean DataFrame:")
  36. print(single_category_mean)
  37. print("Squeezed mean for single category:")
  38. print(squeezed_category_mean, end='\n\n')
  39. # 240-3、提高内存效率和性能
  40. import pandas as pd
  41. # 创建一个大型DataFrame
  42. large_df = pd.DataFrame({'Value': range(1000000)})
  43. # 提取单列并使用squeeze
  44. squeezed_series = large_df[['Value']].squeeze()
  45. # 检查内存使用
  46. print("Memory usage of original DataFrame:", large_df.memory_usage(deep=True).sum())
  47. print("Memory usage of squeezed Series:", squeezed_series.memory_usage(deep=True), end='\n\n')
  48. # 240-4、与函数进行交互
  49. import matplotlib.pyplot as plt
  50. # 定义一个只接受 Series 的绘图函数
  51. def plot_series(series):
  52. series.plot(kind='line', title='Series Plot')
  53. plt.show()
  54. # 提取数据并传递给函数
  55. data = df[['Value']].iloc[0:3] # 提取单列
  56. plot_series(data.squeeze())
  57. # 240-5、简化输出
  58. # 计算平均值并使用squeeze
  59. processed_result = df[['Value']].mean().squeeze()
  60. def display_result(result):
  61. print(f"Processed Result: {result}")
  62. # 使用squeeze简化输出
  63. display_result(processed_result)
  64. # 240-6、数据清洗与转换
  65. import pandas as pd
  66. # 创建一个包含冗余维度的DataFrame
  67. redundant_df = pd.DataFrame({'Value': [[10], [20], [30]]})
  68. # 使用apply和squeeze清理数据
  69. cleaned_series = redundant_df['Value'].apply(lambda x: pd.Series(x).squeeze())
  70. print("Original DataFrame with redundant dimension:")
  71. print(redundant_df)
  72. print("Cleaned Series:")
  73. print(cleaned_series, end='\n\n')
  74. # 240-7、数学与统计计算
  75. import pandas as pd
  76. # 创建一个DataFrame
  77. df = pd.DataFrame({'Value': [10, 20, 30]})
  78. # 计算总和并使用squeeze
  79. total_sum = df[['Value']].sum().squeeze()
  80. print("Total sum of values:", total_sum)
240-6-3、结果输出
  1. # 240、pandas.Series.squeeze方法
  2. # 240-1、从DataFrame提取单行或单列
  3. # Original single column DataFrame:
  4. # A
  5. # 0 10
  6. # 1 20
  7. # 2 30
  8. # Squeezed Series from single column:
  9. # 0 10
  10. # 1 20
  11. # 2 30
  12. # Name: A, dtype: int64
  13. # Original single row DataFrame:
  14. # A B
  15. # 0 10 15
  16. # Squeezed Series from single row:
  17. # A 10
  18. # B 15
  19. # Name: 0, dtype: int64
  20. # 240-2、数据分组后的操作
  21. # Grouped mean DataFrame:
  22. # Value
  23. # Category
  24. # A 15.0
  25. # Squeezed mean for single category:
  26. # 15.0
  27. # 240-3、提高内存效率和性能
  28. # Memory usage of original DataFrame: 8000132
  29. # Memory usage of squeezed Series: 8000132
  30. # 240-4、与函数进行交互
  31. # 见图1
  32. # 240-5、简化输出
  33. # Processed Result: 20.0
  34. # 240-6、数据清洗与转换
  35. # Original DataFrame with redundant dimension:
  36. # Value
  37. # 0 [10]
  38. # 1 [20]
  39. # 2 [30]
  40. # Cleaned Series:
  41. # 0 10
  42. # 1 20
  43. # 2 30
  44. # Name: Value, dtype: int64
  45. # 240-7、数学与统计计算
  46. # Total sum of values: 60

图1:

二、推荐阅读

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

闽ICP备14008679号