我有一个csv文件,该文件是:
Sl. No,City,Name of the Scheme,Completed
1,Chennai,Collector Nagar + 8 slums,285
2,Chennai,Telugu & Tamil Harijan Colony ,138
3,Chennai,Kannabiran Koil Street + 2 Slums,95
4,Coimbatore,Machampalayam Mariamman Koil Stret and Kurichi Boyer Street,223
我的代码:
import sys
import pandas as pd
path = "/home/aviral/dev/local_sink/socialcops/datasets/opendata/config/file-upload-csv_kZCcyHvHM.csv/5bf7e7cf0ca1c9000712f3c1.csv"
df = pd.read_csv(path)
headers = list(df)
counter = 0
for row in df.itertuples(index=False):
row = row._asdict()
print(row)
if counter > 10:
sys.exit()
counter += 1
我得到的输出是:
OrderedDict([('_0', '1'), ('City', 'Chennai'), ('_2', 'Collector Nagar + 8 slums'), ('Completed', 285)])
OrderedDict([('_0', '2'), ('City', 'Chennai'), ('_2', 'Telugu & Tamil Harijan Colony '), ('Completed', 138)])
OrderedDict([('_0', '3'), ('City', 'Chennai'), ('_2', 'Kannabiran Koil Street + 2 Slums'), ('Completed', 95)])
OrderedDict([('_0', '4'), ('City', 'Coimbatore'), ('_2', 'Machampalayam Mariamman Koil Stret and Kurichi Boyer Street'), ('Completed', 223)])
OrderedDict([('_0', '5'), ('City', 'Erode '), ('_2', 'Kamaraj Nagar '), ('Completed', 50)])
OrderedDict([('_0', '6'), ('City', 'Dindigul '), ('_2', 'East Mariyanathapuram '), ('Completed', 168)])
OrderedDict([('_0', '7'), ('City', 'Madurai'), ('_2', 'Anaiyur '), ('Completed', 305)])
OrderedDict([('_0', '8'), ('City', 'Madurai'), ('_2', 'Ahimsapuram + 2 slums'), ('Completed', 498)])
OrderedDict([('_0', '9'), ('City', 'Salem'), ('_2', 'Anna Nagar + 8 Slums '), ('Completed', 1073)])
OrderedDict([('_0', '10'), ('City', 'Trichy '), ('_2', 'Keela Devadhanam + 13 slums'), ('Completed', 938)])
OrderedDict([('_0', '11'), ('City', 'Thoothukudi '), ('_2', 'Kakanji Nagar + 3 slums'), ('Completed', 205)])
OrderedDict([('_0', '12'), ('City', 'Tirunelveli '), ('_2', 'Thiruvannathapuram Pottal + 11 Slums'), ('Completed', 208)])
注意:上面名为'Sl。的任何行中都没有键。否”,而在标题列表中,数据框确实显示同一列。
答案 0 :(得分:1)
之所以这样做,是因为列名中有无效字符,internal class MyException : Exception
{
...
}
无法识别。来自df.itertuples
的熊猫文档:
如果列名被重命名为位置名 无效的Python标识符(重复出现或以下划线开头)。 包含大量列(> 255)的情况下,将返回常规元组。
如果您在代码中的循环之前添加以下行以删除空格和句点,则它将打印列名:
itertuples