从多个列中列出pandas数据帧行值

时间:2017-03-25 23:09:47

标签: python pandas dataframe

我在pandas.DataFrame

中有这些数据
Date, Team1, Team2, Team1 Score, Team2 Score, Event
8/2/17, Juventus, Milan, 2, 1, Friendly match
6/2/17, Milan, Napoli, 3, 0, Friendly match
5/1/17, Milan, Sampdoria, 1, 0, Friendly match
25/12/16, Parma, Milan, 0, 5, Friendly match

如何列出米兰得分目标?

输出应该看起来像::

[1, 3, 1, 5]

6 个答案:

答案 0 :(得分:7)

您可以使用numpy数组' boolean indexing,这里使用values来获取2D numpy数组并使用布尔索引来获取TeamMilan的值:

df[["Team1 Score", "Team2 Score"]].values[df[["Team1", "Team2"]] == "Milan"]
# array([1, 3, 1, 5])

答案 1 :(得分:5)

这将完成这项工作:

product

输出为pd.concat([df["Team1 Score"][df.Team1=='Milan'],df["Team2 Score"][df.Team2=='Milan']]).sort_index().values.tolist()

答案 2 :(得分:5)

# slice df with just team columns and get values
t = df[['Team1', 'Team2']].values

# find the row and column slices where equal to 'Milan'
i, j = np.where(t == 'Milan')

# then slice the scores array with those positions
s = df[['Team1 Score', 'Team2 Score']].values

s[i, j]

array([1, 3, 1, 5])

我可以进一步压缩它,因为我知道所有列都在哪里

v = df.values
i, j = np.where(v[:, [1, 2]] == 'Milan')
v[:, [3, 4]][i, j]

array([1, 3, 1, 5])

答案 3 :(得分:4)

Milano squadra mia

df['tmp1'] = df.loc[df.Team1 == 'Milan', 'Team1 Score']
df['tmp2'] = df.loc[df.Team2 == 'Milan', 'Team2 Score']
df['milazzo'] = df.tmp1.fillna(0) + df.tmp2.fillna(0)
df.milazzo.tolist()

In [73]: df.milazzo.tolist()
Out[73]: [1.0, 3.0, 1.0, 5.0]

答案 4 :(得分:2)

您也可以使用apply:

outlist = df[(df['Team1'] == 'Milan') | (df['Team2'] == 'Milan')].apply(
    lambda k: k['Team1 Score'] if k['Team1'] == 'Milan' else k['Team2 Score'], axis=1
    ).tolist()

答案 5 :(得分:2)

您可以使用pandas.DataFrame.apply()函数在任一列中为团队返回匹配项。

<强>代码:

def get_team_score(team):
    def f(row):
        if row.Team1 == team:
            return row['Team1 Score']
        if row.Team2 == team:
            return row['Team2 Score']

    return f

测试代码:

from io import StringIO

df = pd.read_csv(data)
print(df)
print(df.apply(get_team_score('Milan'), axis=1).values)

测试数据:

import pandas as pd

data = StringIO(u"""Date,Team1,Team2,Team1 Score,Team2 Score,Event  
  8/2/17,Juventus,Milan,2,1,Friendly match
  6/2/17,Milan,Napoli,3,0,Friendly match
  5/1/17,Milan,Sampdoria,1,0,Friendly match
  25/12/16,Parma,Milan,0,5,Friendly match
""")

<强>结果:

       Date     Team1      Team2  Team1 Score  Team2 Score           Event
0    8/2/17  Juventus      Milan            2            1  Friendly match
1    6/2/17     Milan     Napoli            3            0  Friendly match
2    5/1/17     Milan  Sampdoria            1            0  Friendly match
3  25/12/16     Parma      Milan            0            5  Friendly match

[1 3 1 5]