如何在DataFrame的特定cell中插入一个列表list

如何在DataFrame的特定cell中插入一个列表list?

#创建一个list
df = pd.DataFrame({'A': [12, 23], 'B': [23, 34]})
df

    A   B
0  12  23
1  23  34

如果我们想在某个位置插入一个list,让它变成

    A        B
0  [1,23]  23
1  23        34

直接使用ilociat插入会报错

>>> df.iloc[0,0]=[1,2,3]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 671, in __setitem__
    self._setitem_with_indexer(indexer, value)
  File "C:\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1019, in _setitem_with_indexer
    "Must have equal len keys and value "
ValueError: Must have equal len keys and value when setting with an iterable

>>> df.at[0,'A']=[1,2,3]
# 会报错
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 2194, in __setitem__
    self.obj._set_value(*key, takeable=self._takeable)
  File "C:\Anaconda3\lib\site-packages\pandas\core\frame.py", line 3033, in _set_value
    engine.set_value(series._values, index, value)
  File "pandas\_libs\index.pyx", line 96, in pandas._libs.index.IndexEngine.set_value
  File "pandas\_libs\index.pyx", line 109, in pandas._libs.index.IndexEngine.set_value
ValueError: setting an array element with a sequence.

需要先将对应列的Dtype换成 object 后,再使用 at 或者 iat 插入



#先转换成object类型再插入
>>> df['A']=df['A'].astype('object')    # 转换类型
>>> df.info()                           # 确定类型是否转换成功
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   A       2 non-null      object
 1   B       2 non-null      int64
dtypes: int64(1), object(1)
memory usage: 160.0+ bytes
>>> df.at[0,'A']=[1,2,3]              # 尝试插入
>>> df                                # 插入成功
           A   B
0  [1, 2, 3]  23
1         23  34
  • 16
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值