#方法一:使用Python内置的csv模块
import csv
# 打开CSV文件
with open('file.csv', 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
# 遍历每一行数据
for row in reader:
# 处理每一行数据
print(row)
#方法二:使用pandas库
import pandas as pd
# 读取CSV文件
df = pd.read_csv('file.csv', encoding='utf-8')
# 遍历每一行数据
for index, row in df.iterrows():
# 处理每一行数据
print(row)
#方法三:使用numpy库
import numpy as np
# 读取CSV文件
data = np.loadtxt('file.csv', delimiter=',', dtype=str, encoding='utf-8')
# 遍历每一行数据
for row in data:
# 处理每一行数据
print(row)
#方法四:使用Python内置的open方法
#打开CSV文件
with open('file.csv', 'r', encoding='utf-8') as f:
# 遍历每一行数据
for line in f:
# 处理每一行数据
row = line.strip().split(',')
print(row)
import pandas as pd
df = pd.read_csv('a.csv')
df.columns= df.columns.str.strip()
#print(df)
df=df.set_index(keys='SID')
def add_c(xx):
if xx>1:
return '非户主'
else:
return '户主'
df['add_c']=df['COLN'].apply(add_c)
print(df)