0


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

一、用法精讲

306、pandas.Series.str.cat方法
306-1、语法
  1. # 306、pandas.Series.str.cat方法
  2. pandas.Series.str.cat(others=None, sep=None, na_rep=None, join='left')
  3. Concatenate strings in the Series/Index with given separator.
  4. If others is specified, this function concatenates the Series/Index and elements of others element-wise. If others is not passed, then all values in the Series/Index are concatenated into a single string with a given sep.
  5. Parameters:
  6. othersSeries, Index, DataFrame, np.ndarray or list-like
  7. Series, Index, DataFrame, np.ndarray (one- or two-dimensional) and other list-likes of strings must have the same length as the calling Series/Index, with the exception of indexed objects (i.e. Series/Index/DataFrame) if join is not None.
  8. If others is a list-like that contains a combination of Series, Index or np.ndarray (1-dim), then all elements will be unpacked and must satisfy the above criteria individually.
  9. If others is None, the method returns the concatenation of all strings in the calling Series/Index.
  10. sepstr, default ‘’
  11. The separator between the different elements/columns. By default the empty string ‘’ is used.
  12. na_repstr or None, default None
  13. Representation that is inserted for all missing values:
  14. If na_rep is None, and others is None, missing values in the Series/Index are omitted from the result.
  15. If na_rep is None, and others is not None, a row containing a missing value in any of the columns (before concatenation) will have a missing value in the result.
  16. join{‘left’, right’, outer’, inner’}, default left
  17. Determines the join-style between the calling Series/Index and any Series/Index/DataFrame in others (objects without an index need to match the length of the calling Series/Index). To disable alignment, use .values on any Series/Index/DataFrame in others.
  18. Returns:
  19. str, Series or Index
  20. If others is None, str is returned, otherwise a Series/Index (same type as caller) of objects is returned.
306-2、参数

306-2-1、others**(可选,默认值为None)**表示要与当前Series合并的其他Series,可以是一个Series对象的列表,或者是单个Series。

306-2-2、sep**(可选,默认值为None)**用于连接字符串的分隔符,若为None,则不使用分隔符。

306-2-3、na_rep**(可选,默认值为None)**指定如何表示缺失值(NaN),若为None,则缺失值不会被替代。

306-2-4、join**(可选,默认值为'left')**指定合并方式,选项有:

306-2-4-1、'left':仅包含左侧Series中存在的索引。

306-2-4-2、'right':仅包含右侧Series中存在的索引。

306-2-4-3、'outer':包含所有索引(并集)。

306-2-4-4、'inner':仅包含所有Series中都存在的索引(交集)。

306-3、功能
  1. 用于将多个字符串序列按指定的分隔符连接成一个新的字符串序列,它可以处理多个字符串列的合并,并提供了灵活的参数选项以满足不同的需求。
306-4、返回值
  1. 返回一个新的Series对象,其中每个元素都是合并后的字符串。
306-5、说明
  1. 使用场景:

306-5-1、数据整合:在数据分析中,通常需要将来自不同数据源的字符串数据合并。例如,将不同字段的信息合并为一个完整的描述字段,假设有两个Series分别包含用户的名字和姓氏,可以使用该方法将它们合并为全名。

306-5-2、生成报告或日志:当生成报告或日志时,可能需要将多个信息字段合并为一个字符串。例如,在日志记录中,你可能需要将时间戳、事件类型和消息内容合并为一个完整的日志条目。

306-5-3、数据清理:在数据清理过程中,可能会需要将不同列中的字符串合并,以便进一步分析或建模。例如,将地址的各个组成部分(街道、城市、州、邮政编码)合并为一个完整的地址字段。

306-5-4、特征工程:在机器学习中的特征工程阶段,可能会需要将多个特征列的字符串合并为一个特征,以便更好地捕捉数据中的模式。例如,将用户的兴趣爱好、职业和教育背景合并为一个综合的特征,用于模型训练。

306-5-5、数据可视化:在数据可视化过程中,可能需要将数据的不同部分合并为一个标签或标题,以提高图表的可读性。例如,将产品名称、类别和价格合并为图表中的标签。

306-5-6、数据格式化:在处理数据导出或报告生成时,可能需要将多个数据项合并为特定格式的字符串。例如,将日期、时间和地点合并为一个格式化的事件字符串。

306-6、用法
306-6-1、数据准备
306-6-2、代码示例
  1. # 306、pandas.Series.str.cat方法
  2. # 306-1、数据整合:合并用户的名字和姓氏
  3. import pandas as pd
  4. # 创建包含名字和姓氏的Series
  5. first_names = pd.Series(['John', 'Jane', 'Alice'])
  6. last_names = pd.Series(['Doe', 'Smith', 'Johnson'])
  7. # 合并名字和姓氏为全名
  8. full_names = first_names.str.cat(last_names, sep=' ')
  9. print(full_names, end='\n\n')
  10. # 306-2、生成报告或日志:合并时间戳、事件类型和消息内容
  11. import pandas as pd
  12. # 创建包含时间戳、事件类型和消息内容的Series
  13. timestamps = pd.Series(['2024-08-08 12:00', '2024-08-08 12:05'])
  14. event_types = pd.Series(['INFO', 'ERROR'])
  15. messages = pd.Series(['System started', 'Failed to connect'])
  16. # 合并为完整的日志条目
  17. logs = timestamps.str.cat([event_types, messages], sep=' - ')
  18. print(logs, end='\n\n')
  19. # 306-3、数据清理:合并地址的各个组成部分
  20. import pandas as pd
  21. # 创建包含地址各部分的 Series
  22. street = pd.Series(['123 Main St', '456 Maple Ave'])
  23. city = pd.Series(['Springfield', 'Hometown'])
  24. state = pd.Series(['IL', 'CA'])
  25. zip_code = pd.Series(['62701', '90210'])
  26. # 合并为完整的地址
  27. addresses = street.str.cat([city, state, zip_code], sep=', ')
  28. print(addresses, end='\n\n')
  29. # 306-4、特征工程:合并用户的兴趣爱好、职业和教育背景
  30. import pandas as pd
  31. # 创建包含用户兴趣爱好、职业和教育背景的Series
  32. interests = pd.Series(['Reading, Hiking', 'Cooking, Traveling'])
  33. occupations = pd.Series(['Engineer', 'Teacher'])
  34. education = pd.Series(['PhD', 'Masters'])
  35. # 合并为综合特征
  36. features = interests.str.cat([occupations, education], sep=' | ')
  37. print(features, end='\n\n')
  38. # 306-5、数据可视化:生成条形图的标签
  39. import pandas as pd
  40. import matplotlib.pyplot as plt
  41. # 创建包含产品名称、类别和价格的Series
  42. product_names = pd.Series(['Laptop', 'Smartphone', 'Tablet'])
  43. categories = pd.Series(['Electronics', 'Electronics', 'Electronics'])
  44. prices = pd.Series(['$999', '$699', '$399'])
  45. # 合并为图表标签
  46. labels = product_names.str.cat([categories, prices], sep=' - ')
  47. # 创建一个示例数据框
  48. data = pd.DataFrame({
  49. 'Products': labels,
  50. 'Sales': [150, 200, 120] # 示例销售数据
  51. })
  52. # 绘制条形图
  53. plt.figure(figsize=(10, 6))
  54. plt.bar(data['Products'], data['Sales'], color='purple')
  55. # 添加标题和标签
  56. plt.title('Product Sales')
  57. plt.xlabel('Product Details')
  58. plt.ylabel('Sales')
  59. # 旋转x轴标签,以便更好地显示
  60. plt.xticks(rotation=45, ha='right')
  61. # 显示图形
  62. plt.tight_layout()
  63. plt.show()
  64. # 306-6、数据格式化:合并日期、时间和地点
  65. import pandas as pd
  66. # 创建包含日期、时间和地点的Series
  67. dates = pd.Series(['2024-08-08', '2024-08-09'])
  68. times = pd.Series(['09:00', '15:00'])
  69. locations = pd.Series(['Conference Room A', 'Meeting Hall B'])
  70. # 合并为格式化的事件字符串
  71. events = dates.str.cat([times, locations], sep=' ')
  72. print(events)
306-6-3、结果输出
  1. # 306、pandas.Series.str.cat方法
  2. # 306-1、数据整合:合并用户的名字和姓氏
  3. # 0 John Doe
  4. # 1 Jane Smith
  5. # 2 Alice Johnson
  6. # dtype: object
  7. # 306-2、生成报告或日志:合并时间戳、事件类型和消息内容
  8. # 0 2024-08-08 12:00 - INFO - System started
  9. # 1 2024-08-08 12:05 - ERROR - Failed to connect
  10. # dtype: object
  11. # 306-3、数据清理:合并地址的各个组成部分
  12. # 0 123 Main St, Springfield, IL, 62701
  13. # 1 456 Maple Ave, Hometown, CA, 90210
  14. # dtype: object
  15. # 306-4、特征工程:合并用户的兴趣爱好、职业和教育背景
  16. # 0 Reading, Hiking | Engineer | PhD
  17. # 1 Cooking, Traveling | Teacher | Masters
  18. # dtype: object
  19. # 306-5、数据可视化:生成条形图的标签
  20. # 见图1
  21. # 306-6、数据格式化:合并日期、时间和地点
  22. # 0 2024-08-08 09:00 Conference Room A
  23. # 1 2024-08-09 15:00 Meeting Hall B
  24. # dtype: object

图1:

307、pandas.Series.str.center方法
307-1、语法
  1. # 307、pandas.Series.str.center方法
  2. pandas.Series.str.center(width, fillchar=' ')
  3. Pad left and right side of strings in the Series/Index.
  4. Equivalent to str.center().
  5. Parameters:
  6. width
  7. int
  8. Minimum width of resulting string; additional characters will be filled with fillchar.
  9. fillchar
  10. str
  11. Additional character for filling, default is whitespace.
  12. Returns:
  13. Series/Index of objects.
307-2、参数

307-2-1、with**(必须)**指定结果字符串的总宽度,如果字符串的长度小于width,则在字符串的两侧填充fillchar以达到指定的宽度;如果字符串的长度大于或等于width,则返回原始字符串。

307-2-2、fillchar**(可选,默认值为空格字符' ')**用于填充的字符,该字符将会被添加到字符串的左右两侧,以便将字符串扩展到指定的宽度。需要注意的是,fillchar必须是一个长度为1的字符。

307-3、功能
  1. 用于将每个字符串元素居中对齐,该方法常用于需要对字符串进行格式化时,尤其是当你希望字符串在某个宽度内居中显示时。
307-4、返回值
  1. SeriesIndex,具体取决于调用方法的对象。每个元素都被扩展或保持原样,以便其长度达到指定的width;如果某个元素的长度已经等于或超过width,则该元素将不被修改。
307-5、说明
  1. 使用场景:

307-5-1、文本对齐与格式化:在需要将文本居中对齐的场景中,此方法非常实用,无论是生成报表、打印输出还是构建文本表格,都需要确保每个文本单元格式统一、对齐整齐,通过使用该方法可以轻松地将字符串居中并填充左右两侧的空白,达到视觉上更美观的效果。

307-5-2、数据标准化:在数据清洗的过程中,经常会遇到不规则长度的字符串,为了后续处理的方便,有时需要将这些字符串统一为相同长度,该方法通过在字符串两侧添加指定字符,可以将所有字符串标准化为相同长度,从而简化数据处理过程。

307-5-3、文本界面显示:在命令行或控制台应用程序中,通常需要以美观的方式显示文本内容。例如,显示标题、菜单选项或提示信息时,通过使用该方法将文本居中,可以使界面更加整齐、美观。

307-5-4、报表生成:在生成文本报表或导出表格时,为了使各列数据对齐,可以使用该方法对数据进行格式化,通过统一每列数据的宽度,并将内容居中显示,报表看起来会更加规范和专业。

307-5-5、美观的用户界面:如果你在设计用户界面时需要展示一组居中的文本元素,例如按钮或标签,可以使用该方法将文本居中,使整个界面看起来更对称和美观。

307-6、用法
307-6-1、数据准备
307-6-2、代码示例
  1. # 307、pandas.Series.str.center方法
  2. # 307-1、文本对齐与格式化
  3. import pandas as pd
  4. # 创建列标题
  5. headers = pd.Series(['Product Name', 'Price', 'Quantity'])
  6. # 将列标题居中对齐并填充空格
  7. centered_headers = headers.str.center(20)
  8. print(centered_headers, end='\n\n')
  9. # 307-2、数据标准化
  10. import pandas as pd
  11. # 创建公司名称列表
  12. companies = pd.Series(['Apple', 'Microsoft', 'Google', 'Amazon'])
  13. # 将公司名称居中对齐并填充'*',统一长度为15个字符
  14. centered_companies = companies.str.center(15, '*')
  15. print(centered_companies, end='\n\n')
  16. # 307-3、文本界面显示
  17. import pandas as pd
  18. # 创建菜单选项列表
  19. menu_options = pd.Series(['Start Game', 'Options', 'Quit'])
  20. # 将菜单选项居中对齐并填充'-'
  21. centered_menu = menu_options.str.center(30, '-')
  22. print(centered_menu, end='\n\n')
  23. # 307-4、报表生成
  24. import pandas as pd
  25. # 创建报表数据
  26. data = {
  27. 'Product': ['Laptop', 'Smartphone', 'Tablet', 'Monitor'],
  28. 'Price': [999.99, 699.99, 499.99, 199.99],
  29. 'Quantity': [10, 20, 15, 7]
  30. }
  31. # 创建DataFrame
  32. df = pd.DataFrame(data)
  33. # 对Product列进行居中对齐并填充空格
  34. df['Product'] = df['Product'].str.center(15)
  35. # 打印格式化后的报表
  36. print(df, end='\n\n')
  37. # 307-5、美观的用户界面
  38. import pandas as pd
  39. # 创建按钮标签列表
  40. buttons = pd.Series(['OK', 'Cancel', 'Apply'])
  41. # 将按钮标签居中对齐并填充'=',统一长度为10个字符
  42. centered_buttons = buttons.str.center(10, '=')
  43. print(centered_buttons)
307-6-3、结果输出
  1. # 307、pandas.Series.str.center方法
  2. # 307-1、文本对齐与格式化
  3. # 0 Product Name
  4. # 1 Price
  5. # 2 Quantity
  6. # dtype: object
  7. # 307-2、数据标准化
  8. # 0 *****Apple*****
  9. # 1 ***Microsoft***
  10. # 2 *****Google****
  11. # 3 *****Amazon****
  12. # dtype: object
  13. # 307-3、文本界面显示
  14. # 0 ----------Start Game----------
  15. # 1 -----------Options------------
  16. # 2 -------------Quit-------------
  17. # dtype: object
  18. # 307-4、报表生成
  19. # Product Price Quantity
  20. # 0 Laptop 999.99 10
  21. # 1 Smartphone 699.99 20
  22. # 2 Tablet 499.99 15
  23. # 3 Monitor 199.99 7
  24. # 307-5、美观的用户界面
  25. # 0 ====OK====
  26. # 1 ==Cancel==
  27. # 2 ==Apply===
  28. # dtype: object
308、pandas.Series.str.contains函数
308-1、语法
  1. # 308、pandas.Series.str.contains函数
  2. pandas.Series.str.contains(pat, case=True, flags=0, na=None, regex=True)
  3. Test if pattern or regex is contained within a string of a Series or Index.
  4. Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index.
  5. Parameters:
  6. patstr
  7. Character sequence or regular expression.
  8. casebool, default True
  9. If True, case sensitive.
  10. flagsint, default 0 (no flags)
  11. Flags to pass through to the re module, e.g. re.IGNORECASE.
  12. nascalar, optional
  13. Fill value for missing values. The default depends on dtype of the array. For object-dtype, numpy.nan is used. For StringDtype, pandas.NA is used.
  14. regexbool, default True
  15. If True, assumes the pat is a regular expression.
  16. If False, treats the pat as a literal string.
  17. Returns:
  18. Series or Index of boolean values
  19. A Series or Index of boolean values indicating whether the given pattern is contained within the string of each element of the Series or Index.
308-2、参数

308-2-1、pat**(必须)**指定要匹配的模式或字符串,这是你要在Series中查找的字符串模式,可以是简单的字符串或正则表达式。

308-2-2、case**(可选,默认值为True)**指定是否区分大小写,如果为True,则匹配时区分大小写;如果为False,则忽略大小写。

308-2-3、flags**(可选,默认值为0)**控制正则表达式匹配的标志,用于修改正则表达式的行为。例如,re.IGNORECASE(flags=re.I)可以与case=False类似,实现忽略大小写的匹配。

308-2-4、na**(可选,默认值为None)**指定在Series元素为缺失值时返回的布尔值,如果设置为True或False,缺失值将被替换为该布尔值;如果设置为None,缺失值将保持不变。

308-2-5、regex**(可选,默认值为True)**指定pat是否作为正则表达式进行处理,如果为True,则pat将被解释为正则表达式;如果为False,pat将被解释为普通的字符串。如果你不需要使用正则表达式,可以将其设置为False,以提高匹配速度。

308-3、功能
  1. 用于检查每个字符串元素是否包含特定的模式(pat),并返回布尔值(TrueFalse)的Series,用于标识每个元素是否包含该模式。
308-4、返回值
  1. 返回一个布尔值的Series,每个元素对应原Series的一个元素,如果该元素包含匹配的模式,则返回True,否则返回False
308-5、说明
  1. 使用场景:

308-5-1、数据筛选与过滤:在一列包含字符串的数据中,查找包含特定关键词的行。例如,从新闻标题中筛选出包含某个关键词的文章。

308-5-2、数据清洗与预处理:检查数据中的字符串是否符合预期的模式。例如,检查电子邮件字段是否包含“@”符号,以识别无效的电子邮件地址。

308-5-3、特征工程:在构建机器学习模型时,将字符串数据中的模式匹配结果作为特征。例如,判断客户评论中是否包含正面或负面的关键词。

308-5-4、异常值检测:在文本数据中识别不常见或异常的模式。例如,在地址字段中检查是否包含无效字符或格式。

308-5-5、分类与标记:根据特定模式对数据进行分类或标记。例如,根据文章标题中是否包含“Breaking”来标记紧急新闻。

308-5-6、数据对比:比较不同数据源中的字符串字段,找出共同特征或差异。例如,比较用户输入的地址与标准地址列表是否匹配。

308-5-7、正则表达式的应用:通过正则表达式匹配复杂的字符串模式。例如,提取日志文件中的特定日志类型或错误信息。

308-6、用法
308-6-1、数据准备
308-6-2、代码示例
  1. # 308、pandas.Series.str.contains函数
  2. # 308-1、数据筛选与过滤
  3. import pandas as pd
  4. # 示例数据
  5. data = pd.Series(['apple pie', 'banana bread', 'apple juice', 'grape soda'])
  6. # 筛选包含“apple”的行
  7. apple_products = data[data.str.contains('apple')]
  8. print(apple_products, end='\n\n')
  9. # 308-2、数据清洗与预处理
  10. import pandas as pd
  11. # 示例数据
  12. emails = pd.Series(['test@example.com', 'invalidemail.com', 'user@domain.com', 'another.invalidemail'])
  13. # 筛选不包含“@”符号的行
  14. invalid_emails = emails[~emails.str.contains('@')]
  15. print(invalid_emails, end='\n\n')
  16. # 308-3、特征工程
  17. import pandas as pd
  18. # 示例数据
  19. data = pd.DataFrame({
  20. 'review': ['This is good', 'Very bad experience', 'Good value for money', 'Not good at all']
  21. })
  22. # 创建一个新特征,表示评论中是否包含“good”
  23. data['contains_good'] = data['review'].str.contains('good', case=False)
  24. print(data, end='\n\n')
  25. # 308-4、异常值检测
  26. import pandas as pd
  27. # 示例数据
  28. addresses = pd.Series(['123 Main St.', '456 Elm St.', '!@#$% Invalid', '789 Oak St.'])
  29. # 查找包含无效字符的地址
  30. invalid_addresses = addresses[addresses.str.contains('[!@#$%^&*()]', regex=True)]
  31. print(invalid_addresses, end='\n\n')
  32. # 308-5、分类与标记
  33. import pandas as pd
  34. # 示例数据
  35. data = pd.DataFrame({
  36. 'title': ['Breaking News: Market Crash', 'Daily Update', 'Breaking: New Law Passed', 'Weather Report']
  37. })
  38. # 标记标题中包含“Breaking”的行
  39. data['is_breaking'] = data['title'].str.contains('Breaking')
  40. print(data, end='\n\n')
  41. # 308-6、数据对比
  42. import pandas as pd
  43. # 示例数据
  44. user_addresses = pd.Series(['123 Main St.', '456 Elm St.', '789 Oak St.', 'Unknown Address'])
  45. standard_addresses = ['123 Main St.', '456 Elm St.', '789 Oak St.']
  46. # 筛选出与标准地址匹配的用户输入地址
  47. matched_addresses = user_addresses[user_addresses.str.contains('|'.join(standard_addresses))]
  48. print(matched_addresses, end='\n\n')
  49. # 308-7、正则表达式的应用
  50. import pandas as pd
  51. # 示例数据
  52. logs = pd.Series(['INFO: System running', 'ERROR: Disk full', 'INFO: Backup completed', 'ERROR: Network down'])
  53. # 提取包含“ERROR”的日志行
  54. error_logs = logs[logs.str.contains('ERROR')]
  55. print(error_logs)
308-6-3、结果输出
  1. # 308、pandas.Series.str.contains函数
  2. # 308-1、数据筛选与过滤
  3. # 0 apple pie
  4. # 2 apple juice
  5. # dtype: object
  6. # 308-2、数据清洗与预处理
  7. # 1 invalidemail.com
  8. # 3 another.invalidemail
  9. # dtype: object
  10. # 308-3、特征工程
  11. # review contains_good
  12. # 0 This is good True
  13. # 1 Very bad experience False
  14. # 2 Good value for money True
  15. # 3 Not good at all True
  16. # 308-4、异常值检测
  17. # 2 !@#$% Invalid
  18. # dtype: object
  19. # 308-5、分类与标记
  20. # title is_breaking
  21. # 0 Breaking News: Market Crash True
  22. # 1 Daily Update False
  23. # 2 Breaking: New Law Passed True
  24. # 3 Weather Report False
  25. # 308-6、数据对比
  26. # 0 123 Main St.
  27. # 1 456 Elm St.
  28. # 2 789 Oak St.
  29. # dtype: object
  30. # 308-7、正则表达式的应用
  31. # 1 ERROR: Disk full
  32. # 3 ERROR: Network down
  33. # dtype: object
309、pandas.Series.str.count方法
309-1、语法
  1. # 309、pandas.Series.str.count方法
  2. pandas.Series.str.count(pat, flags=0)
  3. Count occurrences of pattern in each string of the Series/Index.
  4. This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the Series.
  5. Parameters:
  6. pat
  7. str
  8. Valid regular expression.
  9. flags
  10. int, default 0, meaning no flags
  11. Flags for the re module. For a complete list, see here.
  12. **kwargs
  13. For compatibility with other string methods. Not used.
  14. Returns:
  15. Series or Index
  16. Same type as the calling object containing the integer counts.
309-2、参数

309-2-1、pat**(必须)**一个正则表达式模式,用于匹配字符串中的子字符串,可以是简单的字符,也可以是复杂的正则表达式。

309-2-2、flags**(可选,默认值为0)**用于正则表达式的标志,可以修改正则表达式的行为,常用的标志包括:

  • re.IGNORECASE或re.I:忽略大小写匹配。
  • re.MULTILINE或re.M:将每行视为单独的字符串,允许^和$匹配每行的开始和结束。
  • re.DOTALL或re.S:. 匹配包括换行符在内的所有字符。
  • re.VERBOSE或re.X:允许你写更具可读性的正则表达式。
309-3、功能
  1. 对每个字符串值应用正则表达式模式,并返回该模式在字符串中出现的次数,它可以用于整个Series,也就是每个字符串元素都会单独计算匹配次数。
309-4、返回值
  1. 返回一个与原始Series 具有相同索引的新的Series,每个元素都是一个整数,表示pat在相应字符串中出现的次数。
309-5、说明
309-6、用法
309-6-1、数据准备
309-6-2、代码示例
  1. # 309、pandas.Series.str.count方法
  2. # 309-1、基本用法
  3. import pandas as pd
  4. # 示例数据
  5. data = pd.Series(['apple', 'banana', 'cherry', 'date', 'apple pie'])
  6. # 统计每个字符串中 'a' 的出现次数
  7. a_count = data.str.count('a')
  8. print(a_count, end='\n\n')
  9. # 309-2、使用flags参数
  10. import pandas as pd
  11. import re
  12. # 示例数据
  13. data = pd.Series(['Apple', 'banana', 'Cherry', 'Date', 'apple pie'])
  14. # 统计每个字符串中'a'的出现次数,忽略大小写
  15. a_count_case_insensitive = data.str.count('a', flags=re.IGNORECASE)
  16. print(a_count_case_insensitive)
309-6-3、结果输出
  1. # 309、pandas.Series.str.count方法
  2. # 309-1、基本用法
  3. # 0 1
  4. # 1 3
  5. # 2 0
  6. # 3 1
  7. # 4 1
  8. # dtype: int64
  9. # 309-2、使用flags参数
  10. # 0 1
  11. # 1 3
  12. # 2 0
  13. # 3 1
  14. # 4 1
  15. # dtype: int64
310、pandas.Series.str.decode函数
310-1、语法
  1. # 310、pandas.Series.str.decode函数
  2. pandas.Series.str.decode(encoding, errors='strict')
  3. Decode character string in the Series/Index using indicated encoding.
  4. Equivalent to str.decode() in python2 and bytes.decode() in python3.
  5. Parameters:
  6. encoding
  7. str
  8. errors
  9. str, optional
  10. Returns:
  11. Series or Index
310-2、参数

310-2-1、encoding**(必须)**字符串,指定要使用的字符编码类型,例如'utf-8'、'ascii'、'latin-1'等,该参数定义了如何将二进制数据解码为字符串。

310-2-2、errors**(可选,默认值为'strict')**定义在解码过程中遇到错误时的处理方式,可选值如下:

  • 'strict'(默认值):遇到无法解码的字节时会引发一个UnicodeDecodeError。
  • 'ignore':忽略无法解码的字节,不会引发错误,也不会在结果中包含这些字节。
  • 'replace':用替代字符(通常是?或\uFFFD)代替无法解码的字节。
  • 'backslashreplace':将无法解码的字节替换为反斜杠转义序列。
  • 'namereplace':将无法解码的字节替换为\N{...}名称转义序列。
  • 'xmlcharrefreplace':将无法解码的字节替换为XML字符引用。
310-3、功能
  1. 用于对Series对象中的字符串进行解码,该方法会尝试将每个字符串解码为指定的编码,并根据errors参数处理可能的解码错误。
310-4、返回值
  1. 返回一个新的SeriesIndex对象,其中的元素为解码后的字符串,如果解码过程中发生错误,且errors参数设置为'ignore''replace'等,错误处理将影响返回值的内容。
310-5、说明
310-6、用法
310-6-1、数据准备
310-6-2、代码示例
  1. # 310、pandas.Series.str.decode函数
  2. import pandas as pd
  3. # 创建一个Series对象,其中包含以UTF-8编码的字节字符串
  4. s = pd.Series([b'\xe4\xbd\xa0\xe5\xa5\xbd', b'\xe4\xb8\x96\xe7\x95\x8c'])
  5. # 对字节字符串进行解码,使用UTF-8编码
  6. decoded_s = s.str.decode(encoding='utf-8')
  7. print(decoded_s)
310-6-3、结果输出
  1. # 310、pandas.Series.str.decode函数
  2. # 0 你好
  3. # 1 世界
  4. # dtype: object

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页

本文转载自: https://blog.csdn.net/ygb_1024/article/details/141021750
版权归原作者 神奇夜光杯 所有, 如有侵权,请联系我们删除。

“Python酷库之旅-第三方库Pandas(075)”的评论:

还没有评论