Python 将项目添加到 pandas.Series?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20441980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:26:48  来源:igfitidea点击:

Add item to pandas.Series?

pythonpandasseries

提问by Michael

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

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

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'

How can I fix that?

我该如何解决?

采纳答案by alko

Convert appended item to Series:

将附加项目转换为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

or use DataFrame:

或使用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

And you can use numpy as a last resort:

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

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

回答by Gormoruk

set_value shows warning:

set_value 显示警告:

FutureWarning: set_value is deprecated and will be removed in a future release. Please use .at[] or .iat[] accessors instead

FutureWarning: set_value 已弃用,将在未来版本中删除。请改用 .at[] 或 .iat[] 访问器

so you can use 'at' as follows:

所以你可以使用 'at' 如下:

input.at[input.index[-1]+1]=6