Pandas Series.str.get() 方法



Python Pandas 中的Series.str.get() 方法用于从 Series 或索引的每个元素中包含的各种数据结构中提取元素。无论您使用的是列表、元组、字典还是字符串,此方法都允许您指定要提取的元素的位置或键。

它简化了访问嵌套数据的过程,在数据清理和预处理任务中非常有用。

语法

以下是 Pandas Series.str.get() 方法的语法:

Series.str.get(i)

参数

Series.str.get() 方法接受以下参数:

  • i - 表示要提取的元素的位置或键的整数或可哈希字典标签。

返回值

Series.str.get() 方法返回包含提取元素的 Series 或索引。

示例 1

此示例演示使用 Series.str.get() 方法从 DataFrame 列中的列表中提取元素。

import pandas as pd

# Create a DataFrame with a column of lists
df = pd.DataFrame({"A": [[1, 2, 3], [0, 1, 3]], "B": ['Tutorial', 'AEIOU']})

print("Original DataFrame:")
print(df)

# Extract the element at index 1 from each list in column 'A'
df['C'] = df['A'].str.get(1)

print("\nDataFrame after extracting elements from lists in column 'A':")
print(df)

运行上述代码时,会产生以下输出:

Original DataFrame:
           A         B
0  [1, 2, 3]  Tutorial
1  [0, 1, 3]     AEIOU

DataFrame after extracting elements from lists in column 'A':
           A         B  C
0  [1, 2, 3]  Tutorial  2
1  [0, 1, 3]     AEIOU  1

新列“C”包含从列“A”中每个列表的索引 1 提取的元素。

示例 2

此示例演示使用 Series.str.get() 方法从 DataFrame 列中的字符串中提取字符。

import pandas as pd

# Create a DataFrame with a column of strings
df = pd.DataFrame({"A": [[1, 2, 3], [0, 1, 3]], "B": ['Tutorial', 'AEIOU']})

print("Original DataFrame:")
print(df)

# Extract the character at index 1 from each string in column 'B'
df['D'] = df['B'].str.get(1)

print("\nDataFrame after extracting characters from strings in column 'B':")
print(df)

运行上述代码时,会产生以下输出:

Original DataFrame:
           A         B
0  [1, 2, 3]  Tutorial
1  [0, 1, 3]     AEIOU

DataFrame after extracting characters from strings in column 'B':
           A         B  D
0  [1, 2, 3]  Tutorial  u
1  [0, 1, 3]     AEIOU  E

示例 3

此示例演示使用 Series.str.get() 方法从 DataFrame 列中的字典中提取值。

import pandas as pd

# Create a DataFrame with a column of dictionaries
df = pd.DataFrame({"A": [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], "B": ['Dict1', 'Dict2']})

print("Original DataFrame:")
print(df)

# Extract the value associated with key 'a' from each dictionary in column 'A'
df['C'] = df['A'].str.get('a')

print("\nDataFrame after extracting values from dictionaries in column 'A':")
print(df)

运行上述代码时,会产生以下输出:

Original DataFrame:
             A      B
0  {'a': 1, 'b': 2}  Dict1
1  {'a': 3, 'b': 4}  Dict2

DataFrame after extracting values from dictionaries in column 'A':
             A      B  C
0  {'a': 1, 'b': 2}  Dict1  1
1  {'a': 3, 'b': 4}  Dict2  3
python_pandas_working_with_text_data.htm
广告
© . All rights reserved.