本文介绍了在python中读取csv数据为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含以下格式数据的 csv
文件
I have ancsv
file with the data in the following format
1 ,F,1,10,48067
2,M,56,16,70072
3,M,25,15,55117
4,M,45,7,02460
5,M,25,20,55455
6,F,50,9,55117
7,M,35,1,06810
8,M,25,12,11413
9,M,25,17,61614
现在我想读取每行并存储一行一个列表,并将M转换为1和F转换为0.这可以在python中完成
now i want to read each line and store one row in a list and also convert M to 1 and F to 0. How can this be done in python
类似
temp = [1,0,25,17,2414]
推荐答案
像这样:
import csv
result = list()
with open('filepath.csv') as f:
reader = csv.reader(f)
for row in reader:
result.append(list())
for item in row:
if item == 'F'
result[-1].append(0)
elif item == 'M':
result[-1].append(1)
else:
result[-1].append(item)
b $ b
这是一个更短,更漂亮的解决方案:
Here is a shorter and a beautiful solution:
import csv
result = list()
with open('filepath.csv') as f:
reader = csv.reader(f)
for row in reader:
result.append([i if (i!='F' and i!='M') else (0 if i=='F' else 1) for i in row])
注意,我没有测试代码。我只是盲目地在这里直接写。
Note that I didn't test the code. I just blindly wrote it here directly.
这篇关于在python中读取csv数据为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!