将项目添加到pandas.Series? [英] Add item to pandas.Series?

查看:57
本文介绍了将项目添加到pandas.Series?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add an integer to my pandas.Series
Here is my code:

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

运行此命令时,出现以下错误:

When i run this, i get the following error:

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'

我该如何解决?

推荐答案

将附加项转换为Series:

>>> 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

和最后一个选择(如果您的索引没有空白)

and last option if your index is without gaps,

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

您可以将numpy作为最后的手段:

And you can use numpy as a last resort:

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

这篇关于将项目添加到pandas.Series?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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