Pandas:使用namedtuple列表初始化数据框架的简洁方法

Mai*_*Mai 27 dataframe python-2.7 pandas

我是熊猫的新手,所以也许我会问一个非常愚蠢的问题.通常,pandas中数据帧的初始化将是列式的,我在其中放入了具有列名称的键和具有相同长度的列表式对象的值的dict.

但是我想在没有动态连接行的情况下初始化行.假设我有一个namedtuple列表,是否有一个优化的操作,它将直接从它给我一个熊猫数据框?

非常感谢

And*_*den 33

从namedtuple创建系列类似,您可以使用以下_fields属性:

In [11]: Point = namedtuple('Point', ['x', 'y'])

In [12]: points = [Point(1, 2), Point(3, 4)]

In [13]: pd.DataFrame(points, columns=Point._fields)
Out[13]: 
   x  y
0  1  2
1  3  4
Run Code Online (Sandbox Code Playgroud)

假设它们都是相同的类型,在这个例子中都是Points.


fil*_*mor 24

这样做的功能namedtuple,看http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html.

如果您有词典,可以直接使用它

df = pd.DataFrame.from_records(
   [namedtuple_instance1, namedtuple_instance2],
   columns=namedtuple_type._fields
)
Run Code Online (Sandbox Code Playgroud)

对于_fields情况下,你必须从通过列名columns类型的直接财产

df = pd.DataFrame.from_records([dict(a=1, b=2), dict(a=2, b=3)])
Run Code Online (Sandbox Code Playgroud)

  • 公平点,我修复了链接并添加了两个例子. (2认同)

Acu*_*nus 8

为了简化先前的答案,显然没有必要指定._fields。看起来没有必要。这应该是正确的,特别是如果所有输入元组都属于同一类型。这是用 pandas==1.3.4 测试的。

> import collections

> Point = collections.namedtuple('Point', ['x', 'y'])
> points = [Point(1, 2), Point(3, 4)]
> pd.DataFrame(points)
   x  y
0  1  2
1  3  4
Run Code Online (Sandbox Code Playgroud)