How to merge a Series and DataFrame

前端 未结 6 1551
别跟我提以往
别跟我提以往 2020-12-02 08:30

If you came here looking for information on how to merge a DataFrame and Series on the index, please look at this answe

6条回答
  •  甜味超标
    2020-12-02 08:53

    If df is a pandas.DataFrame then df['new_col']= Series list_object of length len(df) will add the or Series list_object as a column named 'new_col'. df['new_col']= scalar (such as 5 or 6 in your case) also works and is equivalent to df['new_col']= [scalar]*len(df)

    So a two-line code serves the purpose:

    df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})
    s = pd.Series({'s1':5, 's2':6})
    for x in s.index:    
        df[x] = s[x]
    
    Output: 
       a  b  s1  s2
    0  1  3   5   6
    1  2  4   5   6
    

提交回复
热议问题