Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a list of pandas dataframe row values from multiple columns

I have this data in a 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 I can make a list of Milan scored goals?

The output should look like::

[1, 3, 1, 5]
like image 633
Juho M Avatar asked Mar 25 '17 23:03

Juho M


People also ask

How to select multiple columns in pandas Dataframe?

Pandas is one of those packages and makes importing and analyzing data much easier. Let’s discuss all different ways of selecting multiple columns in a pandas DataFrame. Given a dictionary which contains Employee entity as keys and list of those entity as values. Select Second to fourth column. Example 2: Select one to another columns.

How to get a list of all the column names in pandas?

Here are two approaches to get a list of all the column names in Pandas DataFrame: First approach: my_list = list(df) Second approach: my_list = df.columns.values.tolist() Later you’ll also see which approach is the fastest to use. The Example. To start with a simple example, let’s create a DataFrame with 3 columns:

How to iterate over the rows of the pandas Dataframe?

Solution #1: In order to iterate over the rows of the Pandas dataframe we can use DataFrame.iterrows () function and then we can append the data of each row to the end of the list. Now we will use the DataFrame.iterrows () function to iterate over each of the row of the given Dataframe and construct a list out of the data of each row.

What is the difference between Python list and pandas Dataframe?

Python list is easy to work with and also list has a lot of in-built functions to do a whole lot of operations on lists. Pandas dataframe’s columns consist of series but unlike the columns, Pandas dataframe rows are not having any similar association.


2 Answers

You can use numpy arrays' boolean indexing, here use values to get a 2D numpy array and use boolean indexing to get the values where Team is Milan:

df[["Team1 Score", "Team2 Score"]].values[df[["Team1", "Team2"]] == "Milan"]
# array([1, 3, 1, 5])
like image 123
Psidom Avatar answered Oct 21 '22 00:10

Psidom


This will do the job:

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

The output is [1, 3, 1, 5]

like image 5
Miriam Farber Avatar answered Oct 21 '22 00:10

Miriam Farber