我想向我的
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'
我该如何解决这个问题?
将附加项目转换为
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])))
使用
set_value
会生成警告:
FutureWarning:set_value 已弃用,并将在将来删除 发布。请改用 .at[] 或 .iat[] 访问器
所以你可以像这样使用
at
:
input.at[input.index[-1]+1]=6
这是一个一行答案它取决于数组的定义方式。如果我们使用Series是一个一维数组。使用数组表示法,例如 x[index] = new value
示例
import pandas as pd
input = pd.Series([1,2,3,4,5])
newval = 7 # say
input[len(input)] = newval
或 如果直接定义数组,请使用追加。
#if input is defined as []
input2 = [1, 2]
#input2[len(input2)] = 3 # does not work
input2.append(3) #works
input2
series.append(s)
自版本 1.4.0 起已弃用。
自 2.0 版起删除(2.0.0(2023 年 4 月 3 日))
pd.concat()
import pandas as pd
s1 = pd.Series([False, False, False], index=[1,0,2] )
s2 = pd.Series( True )
pd.concat([s1, s2], axis=0, ignore_index=True)
>>>
0 False
1 False
2 False
3 True
dtype: bool
pd.concat([s1, s2], axis=0)
>>>
1 False
0 False
2 False
0 True
dtype: bool
添加到 df 中已有的系列,变成 DF + DF:(注意索引和列重命名)
_df = pd.DataFrame( s1, columns=['a'] )
_df
>>>
a
1 False
0 False
2 False
pd.concat([ _df,
s2.to_frame().T.rename({0:'a'},axis=1)
],
ignore_index=True)
>>>
a
0 False
1 False
2 False
3 True