Create Empty Dataframe in Pandas specifying column types

前端 未结 11 1979
萌比男神i
萌比男神i 2020-11-28 08:39

I\'m trying to create an empty data frame with an index and specify the column types. The way I am doing it is the following:

df = pd.DataFrame(index=[\'pbp\         


        
11条回答
  •  误落风尘
    2020-11-28 09:07

    You can do this by passing a dictionary into the DataFrame constructor:

    df = pd.DataFrame(index=['pbp'],
                      data={'contract' : np.full(1, "", dtype=str),
                            'starting_membership' : np.full(1, np.nan, dtype=float),
                            'projected_membership' : np.full(1, np.nan, dtype=int)
                           }
                     )
    

    This will correctly give you a dataframe that looks like:

         contract  projected_membership   starting_membership
    pbp     ""             NaN           -9223372036854775808
    

    With dtypes:

    contract                 object
    projected_membership    float64
    starting_membership       int64
    

    That said, there are two things to note:

    1) str isn't actually a type that a DataFrame column can handle; instead it falls back to the general case object. It'll still work properly.

    2) Why don't you see NaN under starting_membership? Well, NaN is only defined for floats; there is no "None" value for integers, so it casts np.NaN to an integer. If you want a different default value, you can change that in the np.full call.

提交回复
热议问题