[英]How to read the csv file as per header and print the values as per header
I have below csv file .我有以下 csv 文件。 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我正在尝试在代码下方运行并尝试打印所有 3 列
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示例:根据我的 for 循环,当我阅读第一行时,我想打印 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 .但请记住,通常您不应该遍历行,请查看此讨论: iterrows performance issues 。 You might have no choice but try to see if you can implement vectorization or use apply function .您可能别无选择,只能尝试查看是否可以实现矢量化或使用apply 函数。
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.虽然 apply 通常用于执行一些计算,并且应该返回一些东西。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.