Creating a list of pandas row data values ​​from multiple columns

I have this data in 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

How can I make a list of goals scored in Milan?

The result should look like this:

[1, 3, 1, 5]
+6
source share
6 answers

You can use numpyarrays boolean indexing , use here valuesto get a 2D numpy array and use boolean indexing to get values ​​where Team- Milan:

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

This will complete the task:

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

Output signal [1, 3, 1, 5]

+5
source
# 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])
+5

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

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()
+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]
+2
source

Source: https://habr.com/ru/post/1016041/


All Articles