【问题标题】:Add item to pandas.Series?将项目添加到 pandas.Series?
【发布时间】:2020-09-19 08:54:11
【问题描述】:

我想给我的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'

我该如何解决这个问题?

【问题讨论】:

标签: python pandas series


【解决方案1】:

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

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

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

【讨论】:

【解决方案2】:

使用set_value 会产生警告:

FutureWarning:set_value 已弃用,将来会被删除 发布。请改用 .at[] 或 .iat[] 访问器

所以你可以像这样使用at

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

【讨论】:

    【解决方案3】:

    这里是单行答案 这取决于数组是如何定义的。如果我们使用 Series 是一个一维数组。使用数组表示法,例如 x[index] = new value

    例子

    import pandas as pd
    input = pd.Series([1,2,3,4,5])
    newval = 7 # say
    input[len(input)] = newval
    

    或 如果直接定义数组,则使用 append。

    #if input is defined as []
    input2 = [1, 2]
    #input2[len(input2)] = 3 # does not work
    input2.append(3) #works
    input2
    

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2015-07-23
      • 2021-04-12
      • 2018-08-29
      相关资源
      最近更新 更多