Python 使用csv标题索引格式化值
我有一个.csv文件,我需要使它看起来像一个特殊格式的字典,我不能用我需要的方式将我的头绕在必要的循环上。例如,这三行(行[0]是带有我的标签的标题)当前看起来像:Python 使用csv标题索引格式化值,python,csv,formatting,data-cleaning,Python,Csv,Formatting,Data Cleaning,我有一个.csv文件,我需要使它看起来像一个特殊格式的字典,我不能用我需要的方式将我的头绕在必要的循环上。例如,这三行(行[0]是带有我的标签的标题)当前看起来像: 0 outlook,temperature,humidity,windy,result 1 overcast,hot,high,FALSE,yes 2 overcast,cool,normal,TRUE,yes ... {"outlook":"overcast", "temperature":"hot", "humidity":
0 outlook,temperature,humidity,windy,result
1 overcast,hot,high,FALSE,yes
2 overcast,cool,normal,TRUE,yes
...
{"outlook":"overcast", "temperature":"hot", "humidity":"high","windy":"FALSE","result":"yes"},
{"outlook":"overcast", "temperature":"cool", "humidity":"normal","windy":"TRUE","result":"yes"},
...
应该是这样的:
0 outlook,temperature,humidity,windy,result
1 overcast,hot,high,FALSE,yes
2 overcast,cool,normal,TRUE,yes
...
{"outlook":"overcast", "temperature":"hot", "humidity":"high","windy":"FALSE","result":"yes"},
{"outlook":"overcast", "temperature":"cool", "humidity":"normal","windy":"TRUE","result":"yes"},
...
一旦它们被处理和清理干净。我已经很接近了,但使用字典不太正确。我一直在搞熊猫和导入csv,我开始不知道在Py3中实现这一点的最佳方法是什么
谢谢你的帮助。非常感谢。您可以使用:
创建一个像普通读取器一样运行的对象,但将读取的信息映射到dict中,dict的键由可选的
fieldnames参数。fieldnames参数是一个序列,其
元素按顺序与输入数据的字段相关联。
这些元素成为结果字典的键。如果
如果省略fieldnames参数,则字段第一行中的值
csvfile将用作字段名
因此,示例代码是:
import csv
with open('temperature.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
...
那会打印出来的
{"outlook":"overcast", "temperature":"hot", "humidity":"high","windy":"FALSE","result":"yes"},
...
这是完美的,我一直在寻找的东西。当然,我也遇到过它一百万次,但它从来没有点击过。知道为什么它会在字典中显示最后一行作为第一个属性吗:{'result':'yes','outlook':'sunny','湿度':'normal','temperature':'mild','windy':'TRUE'}?这是因为
dict
s没有排序,您无法保证键的顺序。不过,这不会影响你的使用。您可以将结果转换为一个值,然后进行排序。