How to merge a Series and DataFrame

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

    You can easily set a pandas.DataFrame column to a constant. This constant can be an int such as in your example. If the column you specify isn't in the df, then pandas will create a new column with the name you specify. So after your dataframe is constructed, (from your question):

    df = pd.DataFrame({'a':[np.nan, 2, 3], 'b':[4, 5, 6]}, index=[3, 5, 6])
    

    You can just run:

    df['s1'], df['s2'] = 5, 6
    

    You could write a loop or comprehension to make it do this for all the elements in a list of tuples, or keys and values in a dictionary depending on how you have your real data stored.

提交回复
热议问题