以下是一个示例代码,演示如何按匹配顺序多次匹配数据帧中相同的行:
import pandas as pd
# 创建示例数据帧
data = {'Name': ['John', 'Mike', 'Emily', 'John', 'Mike'],
'Age': [25, 30, 35, 25, 30],
'City': ['New York', 'Paris', 'London', 'New York', 'Paris']}
df = pd.DataFrame(data)
# 打印原始数据帧
print("原始数据帧:")
print(df)
# 按照匹配顺序多次匹配相同的行
matches = ['John', 'Mike']
matched_rows = []
for match in matches:
rows = df[df['Name'] == match]
matched_rows.extend(rows.values.tolist())
# 创建新的数据帧,包含多次匹配的行
new_df = pd.DataFrame(matched_rows, columns=df.columns)
# 打印新的数据帧
print("\n多次匹配的数据帧:")
print(new_df)
输出结果如下:
原始数据帧:
Name Age City
0 John 25 New York
1 Mike 30 Paris
2 Emily 35 London
3 John 25 New York
4 Mike 30 Paris
多次匹配的数据帧:
Name Age City
0 John 25 New York
1 John 25 New York
2 Mike 30 Paris
3 Mike 30 Paris
上一篇:按照匹配数量排序
下一篇:按照匹配特定列的方式连接两个文件