How to merge a Series and DataFrame

前端 未结 6 1552
别跟我提以往
别跟我提以往 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:43

    You could construct a dataframe from the series and then merge with the dataframe. So you specify the data as the values but multiply them by the length, set the columns to the index and set params for left_index and right_index to True:

    In [27]:
    
    df.merge(pd.DataFrame(data = [s.values] * len(s), columns = s.index), left_index=True, right_index=True)
    Out[27]:
       a  b  s1  s2
    0  1  3   5   6
    1  2  4   5   6
    

    EDIT for the situation where you want the index of your constructed df from the series to use the index of the df then you can do the following:

    df.merge(pd.DataFrame(data = [s.values] * len(df), columns = s.index, index=df.index), left_index=True, right_index=True)
    

    This assumes that the indices match the length.

提交回复
热议问题