2

I have below csv file . How can i read line by line as per header and print the values

EmpId,EmpName,Age
1,X,21
2,Y,22
3,Z,23

I am trying to run below code and trying to print all the 3 columns

file = pd.read_csv('File.csv',names=[EmpId,EmpName,Age], delimiter=',')

for line in file:
    EmployeeID = EmpID (I want to assign value of EmpId to this variable )
    print(EmployeeID)

Example: as per my for loop when i am reading first line i want to print EmployeeID = 1

Arya
  • 528
  • 6
  • 26

3 Answers3

2

You have several methods:

  1. If you only want the employeeId you can do this
for EmployeeID in file.EmpId:
    # EmployeeID contains the id
    ...
  1. If you want to iterate over the rows and not lose the information of other columns
for index, row in file.iterrows():
    EmployeeID = row["EmpId"]
    # You can access to others columns by row[col]
    ...

But keep in mind that in general you shouldn't iter over the rows, look at this discussion: iterrows performance issues. You might have no choice but try to see if you can implement vectorization or use apply function.

Example apply to print the rows and perform some things:

def rowFunction(row):
    EmployeeId = row["EmpId"]
    print(row)
    ...
    return ...

file.apply(lambda row: rowFunction(row), axis=1)

Although apply is in general used to perform some calculation, and should return something.

SmileyProd
  • 788
  • 4
  • 13
1

there is a lot of methods

file = pd.read_csv('File.csv',names=['EmpId','EmpName','Age'], delimiter=',')
print(file.EmpId)

If u want to use the loop:

for line in file.values:
    print(line[0])  # 0: EmpId, 1:EmpName, 2:Age ...

or

for i in file.EmpId:
    print(i)

or

for i in file.EmpId.values:
    print(i)
梅冬阳
  • 21
  • 3
  • @Thanks a lot for the reply. But i am getting 3 times same output [1 2 3] [1 2 3] [1 2 3] ; But i should be getting only once :[1 2 3] – Arya Aug 26 '19 at 12:39
0
# pandas.read_csv return pandas.DataFrame object, so df is a more common variable name
df = pd.read_csv('File.csv',names=[EmpId,EmpName,Age], delimiter=',')

#iterrows() is a good function to iteration rows in DataFrame
for index, row in df.iterrows():
    EmployeeID = row['EmpID']
    print(EmployeeID)
Hongpei
  • 677
  • 3
  • 13