创建和设置一个Pandas DataFrame的元素到一个列表 [英] Create and set an element of a Pandas DataFrame to a list

查看:185
本文介绍了创建和设置一个Pandas DataFrame的元素到一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pandas DataFrame,我正在逐行创建(我知道,我知道,这不是Pandorable / Pythonic ..)。我正在使用 .loc 创建元素

  output.loc [row_id,col_id] 

,我想将此值设置为空列表[]。

  output.loc [row_id,col_id] = [] 

不幸的是,我收到一个错误,表示我的键和值的大小不匹配(熊猫认为我正在尝试设置值不是



有没有办法这样做?



谢谢!

解决方案

您需要确认两件事:


  1. 正好是该loc的一个条目,

  2. 列具有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:

  1. there is precisely one entry for that loc,
  2. 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屋!

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