如何从元组列表中创建带有索引的Pandas DataFrame [英] How to create pandas DataFrame with index from the list of tuples

查看:135
本文介绍了如何从元组列表中创建带有索引的Pandas DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用记录中的索引创建pandas DataFrame的最佳方法是什么?
这是我的示例:

What would be the best way to create pandas DataFrame with index from records. Here is my sample:

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)

我需要帐户作为此处的索引(而不是列)
谢谢

I need 'Account' to be an index here (not a column) Thanks

推荐答案

最简单的是 set_index

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

或通过列表理解选择:

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

这篇关于如何从元组列表中创建带有索引的Pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆