是否可以以这种格式读取CSV文件:
"name","foo"
"class","9"
"age","34"
"gender","F"
进入这样的结果数据框:
name class age gender
0 foo 9 34 F
答案 0 :(得分:2)
用熊猫:
df = pd.read_csv('myfile.csv', index_col=False, header=None)
df2 = pd.DataFrame(pd.DataFrame(df[1]).T)
header = df[0]
header.name = None
df2.columns = header
df2.index = [0]
现在df2
包含:
name class age gender
0 foo 9 34 F
答案 1 :(得分:0)
是的,请参阅DictReader
>>> import csv
>>> with open('names.csv') as csvfile:
... reader = csv.DictReader(csvfile)
... for row in reader:
... print(row['first_name'], row['last_name'])
答案 2 :(得分:0)
请尝试以下选项。
configreader = csv.DictReader(open(configuration_file_path))
result = {}
for row in configreader:
for column, value in row.iteritems():
result.setdefault(column, []).append(value)
print " ".join(result.keys())
for index in range(len(result["name"])):
print "{0}->{1}-->{2}".format(index, result["name"][index],result["foo"][index])
答案 3 :(得分:0)
如果您将第一列作为标题,第二列作为值,则下面的选项可能很有用
fhandle = open("d:\\a.csv")
result = {}
for row in fhandle:
row = row.strip()
item = row.split(",")
if len(item) > 1:
if item[0] not in result:
result[item[0]] = []
result[item[0]].append(item[1])
print " ".join(result.keys())
for index in range(0,len(result.values()[0])):
for key in result.keys():
print result[key][index] + " ",
print "\n",