gpt4 book ai didi

python - 创建单个 pandas.core.frame.Pandas 对象

转载 作者:行者123 更新时间:2023-12-05 02:39:13 24 4
gpt4 key购买 nike

如何将单行数据创建为 pandas.core.frame.Pandas 对象

因此,当您使用 for row in df.itertuples() 迭代数据帧 (df) 时,每一行都是一个 pandas.core.frame.Pandas 对象.我想创建一个该类型的对象。

例如:

import pandas as pd

d = [{'a': 1, 'b': 2}]
df = pd.DataFrame(d)
print(type(df))
print("a", df.a)

for row in df.itertuples():
print(type(row))
print("a", row.a)


myrow = None
df = pd.DataFrame(d)
for row in df.itertuples():
myrow = row
print(type(myrow))
print("a", myrow.a)

它的输出是:

<class 'pandas.core.frame.DataFrame'>
a 0 1
Name: a, dtype: int64
<class 'pandas.core.frame.Pandas'>
a 1
<class 'pandas.core.frame.Pandas'>
a 1

如您所见,pandas.core.frame.DataFrame 的行为与 pandas.core.frame.Pandas 不同,正如预期的那样。

我真的不想像上面那样创建 myrow ,所以我想知道创建该对象的更有效/直接的方法是什么。假设我只有 1 个数据列表要转换为 pandas.core.frame.Pandas 对象

最佳答案

说明:

itertuples 的每次迭代都会给出如下对象:

Pandas(Index=0, a=1, b=2)

Pandas 只是 itertuples name 参数的默认名称,例如:

>>> help(df.itertuples)
Help on method itertuples in module pandas.core.frame:

itertuples(index=True, name='Pandas') method of pandas.core.frame.DataFrame instance
Iterate over DataFrame rows as namedtuples.

Parameters
----------
index : bool, default True
If True, return the index as the first element of the tuple.
name : str or None, default "Pandas"
The name of the returned namedtuples or None to return regular
tuples.

默认名称是 Pandas。这只是 namedtuple 的名称。

如果您更改该名称,类型将变得不同:

for row in df.itertuples(name='newname'):
print(row)
print(type(row))
print("a", row.a)

输出:

newname(Index=0, a=1, b=2)
<class 'pandas.core.frame.newname'>
a 1

复制:

这是namedtuple的默认行为,例如:

>>> from collections import namedtuple
>>> a = namedtuple('Pandas', ['x', 'y', 'z'])
>>> a(1, 2, 3)
Pandas(x=1, y=2, z=3)
>>> type(_)
<class '__main__.Pandas'>
>>>

可以看到,this的类型是Pandas,也就是这个namedtuple的类型名,所以itertuples不是给一个 Pandas 对象,而不是它只是 itertuples namedtuple 输出的默认集合名称。

文档引用:

collections.namedtuple 中所述文档:

Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

如您所见,它创建了一个新类型。

关于python - 创建单个 pandas.core.frame.Pandas 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69185981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com