Чтобы получить последний столбец после применения операции .str.split()к столбцу в Pandas DataFrame, вы можете использовать следующие методы:
Метод 1: использование .str.split()и .str[-1]
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'column': ['apple, banana, cherry', 'dog, cat, elephant']})
# Split the column and get the last element
df['last_column'] = df['column'].str.split(', ').str[-1]
# Display the DataFrame
print(df)
Выход:
column last_column
0 apple, banana, cherry cherry
1 dog, cat, elephant elephant
Метод 2: использование .str.rsplit()и .str[-1]
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'column': ['apple, banana, cherry', 'dog, cat, elephant']})
# Split the column from the right and get the last element
df['last_column'] = df['column'].str.rsplit(', ', expand=True).iloc[:, -1]
# Display the DataFrame
print(df)
Выход:
column last_column
0 apple, banana, cherry cherry
1 dog, cat, elephant elephant
Метод 3: использование .apply()и лямбда-функции
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'column': ['apple, banana, cherry', 'dog, cat, elephant']})
# Apply a lambda function to split the column and get the last element
df['last_column'] = df['column'].apply(lambda x: x.split(', ')[-1])
# Display the DataFrame
print(df)
Выход:
column last_column
0 apple, banana, cherry cherry
1 dog, cat, elephant elephant