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]
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.
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:
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.
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.
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])
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With