IT源码网

python 将项目添加到 pandas.Series

think 2023年05月15日 程序员 66 0

我想向我的 pandas.Series
添加一个整数 这是我的代码:

import pandas as pd 
input = pd.Series([1,2,3,4,5]) 
input.append(6) 

当我运行它时,出现以下错误:

Traceback (most recent call last): 
  File "<pyshell#9>", line 1, in <module> 
    f.append(6) 
  File "C:\Python33\lib\site-packages\pandas\core\series.py", line 2047, in append 
    verify_integrity=verify_integrity) 
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 878, in concat 
    verify_integrity=verify_integrity) 
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 954, in __init__ 
    self.new_axes = self._get_new_axes() 
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1146, in _get_new_axes 
    concat_axis = self._get_concat_axis() 
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1163, in _get_concat_axis 
    indexes = [x.index for x in self.objs] 
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1163, in <listcomp> 
    indexes = [x.index for x in self.objs] 
AttributeError: 'int' object has no attribute 'index' 

我该如何解决?

请您参考如下方法:

将附加项转换为系列:

>>> ds = pd.Series([1,2,3,4,5])  
>>> ds.append(pd.Series([6])) 
0    1 
1    2 
2    3 
3    4 
4    5 
0    6 
dtype: int64 

或者使用DataFrame:

>>> df = pd.DataFrame(ds) 
>>> df.append([6], ignore_index=True) 
   0 
0  1 
1  2 
2  3 
3  4 
4  5 
5  6 

最后一个选项,如果你的索引没有间隙,

>>> ds.set_value(max(ds.index) + 1,  6) 
0    1 
1    2 
2    3 
3    4 
4    5 
5    6 
dtype: int64 

你可以使用 numpy 作为最后的手段:

>>> import numpy as np 
>>> pd.Series(np.concatenate((ds.values, [6]))) 


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!