Add item to pandas.Series?

前端 未结 3 872
我寻月下人不归
我寻月下人不归 2020-12-15 07:57

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)


        
相关标签:
3条回答
  • 2020-12-15 08:43

    Convert appended item to 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:

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

    >>> import numpy as np
    >>> pd.Series(np.concatenate((ds.values, [6])))
    
    0 讨论(0)
  • 2020-12-15 08:47

    Using set_value generates the warning:

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

    So you can instead use at like this:

    input.at[input.index[-1]+1]=6
    
    0 讨论(0)
  • 2020-12-15 08:57

    here is a one-line answer It is dependent on how the array is defined. If we use Series is a one d array. Use the array notation like x[index] = new value

    example

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

    or use append if the array is being directly defined.

    #if input is defined as []
    input2 = [1, 2]
    #input2[len(input2)] = 3 # does not work
    input2.append(3) #works
    input2
    
    0 讨论(0)
提交回复
热议问题