熊猫多列匹配,然后向后移位以寻找价值



非常感谢您的帮助。我是一个熊猫蟒蛇菜鸟,已经被这个问题扔进了深渊。

我在这个网站上搜索了大约 100 个不同的查询,但找不到合适的东西。我得到的最接近的是应用布尔面具。

请单击下面的文本以查找我的数据框。

我想对数据集运行查询以查找在"HomeTeam"列中找到"AwayTeam"字符串的前一行 ->然后我想为该匹配的发生率提取"home_form"的值作为附加列

日期 主场球队 客队 home_form away_form new_column
队 25/08/2019 斯特拉斯堡 雷恩 1.0 3.0 楠(第25排,仅举个例子(01/09/2019 雷恩尼斯 3.0 3.0 3.0 (第37行,仅举个例子(

我想为主队出现在客队列的最后一行提取之前的"away_form"值

这不是一个完整的解决方案,但我想我找到了一种方法来帮助你取得一些进展。

步骤如下:

  1. 创建示例数据框,仅用于说明
  2. 将"主队"列转换为列表...这是目标列。

  3. 创建一个空列表来存储搜索"HomeTeam"列的结果

  4. 在"客队"列中循环浏览球队

  5. 使用 Python 的 list.index(( 方法返回匹配的索引...但是使用 try-除非以防万一您找不到匹配项。

  6. 将结果存储到列表中

  7. 完成 for 循环后,将列表作为新列添加到 pandas 数据帧中。

import pandas as pd
import numpy as np
# create sample dataframe
df = pd.DataFrame({
'Date': ['2019-08-18', '2019-08-25'], 
'HomeTeam': ['Rennes', 'Strasbourg'],
'AwayTeam': ['Paris SG', 'Rennes'],
'home_form': [np.NaN, 1.0],
'away_form': [np.NaN, 3.0],
})
# convert your 'HomeTeam' column into a Python list
list_HomeTeam = list(df['HomeTeam'])
print(list_HomeTeam)
# create an empty list to capture the index position of matches in 'HomeTeam'
list_results_in_home = []
# loop through each team in the 'AwayTeam column'
for each_team in df['AwayTeam']:
# if you find a match in the list, store index as a result
try:
result = list_HomeTeam.index(each_team)
# if you don't find a match, store a string
except:
result = 'team not in list'
# add the result to the list that is capturing the index position in 'HomeTeam'
list_results_in_home.append(result)
print(list_index_home)
# add column to dataframe with the index position
df['index_match_in_HomeTeam'] = list_results_in_home

相关内容

最新更新