Store values from rows of a DataFrame and use them in another operation

Viewed 124

I have a DataFrame I read from a CSV file and I want to store the individual values from the rows in the DataFrame in some variables. I want to use the values from the DataFrame in another step to perform another operation. Note that I do not want the result as series but values such as integers. I am still learning but I could not understand those resources I have consulted. Thank you in advance.

X Y Z
1 2 3
3 2 1
4 5 6

I want the values in a variable as x=1,3,4 and so on, as stated above.

3 Answers

There are many ways you can do this but one simple method is to use the index method. Other people may give other methods but let me illustrate the index method here. I will create a dictionary and change it to DataFrame from which rows iteration can be performed.

# Start by importing pandas as pd
import pandas as pd

# Proceed by defining a dictionary that contains a player's stats (just for 
ilustration, not real data)
myData = {'Football Club': ['Chelsea', 'Man Utd', 'Inter Milan', 'Everton'],
'Matches Played': [2, 32, 36, 37],
'Goals Scored': [1, 12, 24, 25],
'Assist Given': [0, 0, 11, 6],
'Red card': [0,0,0,0,],
'Yellow Card':[0,4,4,3]}

 # Next create a DataFrame from the dictionary from previous step
 df = pd.DataFrame(myData, columns = ['Football Club', 'Matches Played', 'Goals 
 Scored', 'Red card', 'Yellow Card'])
 
  #See what the data look like.
 print("This is the created Dataframe from the dictionary:\n", df)

 print("\n Now, you can iterate over selected rows or all the rows using 
index 
 attribute as follows:\n")

 #Store the values in variables
 for indIte in df.index:
clubs=df['Football Club'][indIte]
goals =df['Goals Scored'][indIte]
matches=df['Matches Played'][indIte]
#To see the results that can be used later in the same program
print(clubs, matches, goals)

#You will get the following results:
This is the created Dataframe from the dictionary :
Football Club  Matches Played  Goals Scored  Red card  Yellow Card
0       Chelsea               2             1         0            0
1       Man Utd              32            12         0            4
2   Inter Milan              36            24         0            4
3       Everton              37            25         0            3

 Now, you can iterate over selected rows or all the rows using index 
 attribute as follows:

  Chelsea 2 1
  Man Utd 32 12
  Inter Milan 36 24
  Everton 37 25

Use:

x, y, z = df.to_dict(orient='list').values()
>>> x
[1, 3, 4]

>>> y
[2, 2, 5]

>>> z
[3, 1, 6]

df.values is a numpy array of a dataframe. So you can manipulate df.values for subsequent processing.

Related