问题描述
我是熊猫新手,所以也许我在问一个非常愚蠢的问题.通常,大熊猫中数据帧的初始化是按列的,在这里,我用列名的键和长度相同的类似列表的对象的值放入dict.
I'm new to pandas, therefore perhaps I'm asking a very stupid question. Normally initialization of data frame in pandas would be column-wise, where I put in dict with key of column names and values of list-like object with same length.
但是我很想在不动态连接行的情况下按行初始化.说我有一个namedtuple列表,是否有优化的操作可以直接给我一个熊猫数据框?
But I would love to initialize row-wise without dynamically concat-ing rows. Say I have a list of namedtuple, is there a optimized operation that will give me a pandas data frame directly from it?
非常感谢
推荐答案
您想要的功能是 from_records .
对于namedtuple
实例,除了命名元组列表之外,还必须将namedtuple的_fields
属性传递给from_records
的columns
参数:
For namedtuple
instances you must pass the _fields
property of the namedtuple to the columns
parameter of from_records
, in addition to a list of namedtuples:
df = pd.DataFrame.from_records(
[namedtuple_instance1, namedtuple_instance2],
columns=namedtuple_type._fields
)
如果您有字典,可以直接将其用作
If you have dictionaries, you can use it directly as
df = pd.DataFrame.from_records([dict(a=1, b=2), dict(a=2, b=3)])
这篇关于Pandas:一种使用namedtuple列表初始化数据帧的干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!