创建和设置一个Pandas DataFrame的元素到一个列表 [英] Create and set an element of a Pandas DataFrame to a list
问题描述
output.loc [row_id,col_id]
,我想将此值设置为空列表[]。
output.loc [row_id,col_id] = []
不幸的是,我收到一个错误,表示我的键和值的大小不匹配(熊猫认为我正在尝试设置值与不是
有没有办法这样做?
谢谢!
您需要确认两件事:
- 正好是该loc的一个条目,
- 列具有dtype对象(实际上,在测试这似乎不是一个问题)。
这样做的一个奇怪的方法是使用[]:
$在[11]中:df = pd.DataFrame([[1,2],[3,4]],列= ['A' ,'B'])在[12]中:df.loc [[0],'A'] = pd.Series([[]])
[13]:df
出[13]:
AB
0 [] 2
1 3 4
大熊猫不太希望你使用 []
作为元素,因为它通常不是很有效率,并且使聚合更复杂(而不是cythonisable)。
一般来说,你不想逐个建立DataFrames,总有一个更好的方法。
I have a Pandas DataFrame that I'm creating row-by-row (I know, I know, it's not Pandorable/Pythonic..). I'm creating elements using .loc like so
output.loc[row_id, col_id]
and I'd like to set this value to an empty list, [].
output.loc[row_id, col_id] = []
Unfortunately, I get an error saying the size of my keys and values do not match (Pandas thinks I'm trying to set values with not to an iterable).
Is there a way to do this?
Thanks!
You need to make sure two things:
- there is precisely one entry for that loc,
- the column has dtype object (actually, on testing this seems not to be an issue).
A hacky way to do this is to use a Series with []:
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])
In [12]: df.loc[[0], 'A'] = pd.Series([[]])
In [13]: df
Out[13]:
A B
0 [] 2
1 3 4
pandas doesn't really want you use []
as elements because it's usually not so efficient and makes aggregations more complicated (and un-cythonisable).
In general you don't want to build up DataFrames cell-by-cell, there is (almost?) always a better way.
这篇关于创建和设置一个Pandas DataFrame的元素到一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!