1

I have a csv file with place name, score A and Score B, i want to pull the Score A and Score B values of each place. With the help of pandas i read the csv and stored in a DF like below

import pandas as pd
csvdf = pd.read_csv("E:\redsa.csv")
print(csvdf)

I am getting the following output

          Place     ScoreA   ScoreB
0         Place 1   108       775
1         Place 2   109       781

I want to pull Score A and Score B values for each place and store them in separate variables and i tried below for this

for row in csvdf.iterrows():
    print(csvdf['ScoreA'],csvdf['ScoreB'])

I am getting below output

0    108
1    109
Name: ScoreA, dtype: float64 0    775
1    781
Name: ScoreB, dtype: float64
0    108
1    109
Name: ScoreA, dtype: float64 0    775
1    781
Name: ScoreB, dtype: float64

i want to iterate through each place and get the ScoreA and ScoreB and store them in their respective variables, how can i get this done

foret
  • 337
  • 1
  • 5
  • 14

1 Answers1

1

I believe you need apply with axis=1 for loop by rows, because iterrows is best avoid for poor performance, if possible:

def func(x):
    print (x['ScoreA'])
    print (x['ScoreB'])

    #code
    return x

df = csvdf.apply(func, axis=1)
print (df)

You can create index from first Place column by parameter index_col in read_csv and then select columns - output is Series:

csvdf = pd.read_csv("E:\redsa.csv", index_col=[0])

print (csvdf['ScoreA'])
Place
Place 1    108
Place 2    109
Name: ScoreA, dtype: int64

print (csvdf['ScoreB'])
Place
Place 1    775
Place 2    781
Name: ScoreB, dtype: int64

Or select by subsets - output is 2 columns DataFrame:

csvdf = pd.read_csv("E:\redsa.csv")

print (csvdf[['Place','ScoreA']])
     Place  ScoreA
0  Place 1     108
1  Place 2     109

print (csvdf[['Place','ScoreB']])
     Place  ScoreB
0  Place 1     775
1  Place 2     781
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252