如何在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,2,3] 23
1 23 34
直接使用iloc
和iat
插入会报错
>>> 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