下面是一个示例代码,演示了如何保留一个列中以另一列中的字符串结尾的值:
import pandas as pd
# 创建示例数据
data = {'Name': ['John Smith', 'Jane Doe', 'Mark Johnson', 'Sara Thompson'],
'Search': ['Smith', 'Doe', 'Johnson', 'Thompson']}
df = pd.DataFrame(data)
# 使用str.endswith()方法筛选出符合条件的行
df['Result'] = df['Name'][df['Name'].str.endswith(tuple(df['Search']))]
# 打印结果
print(df['Result'])
运行示例代码后,将得到以下输出:
0 John Smith
1 Jane Doe
2 Mark Johnson
3 Sara Thompson
Name: Result, dtype: object
在示例中,我们使用了pandas库来创建一个DataFrame对象,并在其中包含两个列:'Name'和'Search'。然后,我们使用str.endswith()方法来筛选出'Name'列中以'Search'列中的字符串结尾的值,并将结果存储在一个新的'Result'列中。
请注意,str.endswith()方法接受一个字符串或字符串的元组作为参数,因此我们使用tuple()函数将'Search'列转换为元组。这样做是为了确保str.endswith()方法能够正确地处理多个搜索条件。
最后,我们打印出新的'Result'列,以显示筛选出的结果。
上一篇:保留名称和用户字面量
下一篇:保留命令函数中的状态