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

2
  • EmployeeID = line.EmpId? Commented Aug 26, 2019 at 12:31
  • Yes , As i have 3 lines in csv file and when i am running for loop for 3 times in each loop i want to read my 3 column values.. Commented Aug 26, 2019 at 12:32

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

@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]
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)

1 Comment

Please add some explanation to your answer. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.