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
You have several methods:
for EmployeeID in file.EmpId:
# EmployeeID contains the id
...
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.
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)
# 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.