使用记录索引创建pandas DataFrame的最佳方法是什么。 这是我的样本:
sales = [('Jones LLC', 150, 200, 50),
('Alpha Co', 200, 210, 90),
('Blue Inc', 140, 215, 95)]
labels = ['account', 'Jan', 'Feb', 'Mar']
df = pd.DataFrame.from_records(sales, columns=labels)
我需要'帐户'作为索引(不是列) 感谢
答案 0 :(得分:2)
Simpliest is set_index
:
df = pd.DataFrame.from_records(sales, columns=labels).set_index('account')
print (df)
Jan Feb Mar
account
Jones LLC 150 200 50
Alpha Co 200 210 90
Blue Inc 140 215 95
Or select by list comprehensions:
labels = [ 'Jan', 'Feb', 'Mar']
idx = [x[0] for x in sales]
data = [x[1:] for x in sales]
df = pd.DataFrame.from_records(data, columns=labels, index=idx)
print (df)
Jan Feb Mar
Jones LLC 150 200 50
Alpha Co 200 210 90
Blue Inc 140 215 95