Search code examples
pythonpandasdataframeseriesdata-analysis

creating DataFrame from a Data Series


I have a data series,

df,
           primary
Buy        484
Sell       429
Blanks     130
FX Spot    108
Income     77
FX Forward 2

trying to crate a dataframe with 2 column. first column values should be the index of df second column should have the values of primary in df

 by using,
 filter_df=pd.DataFrame({'contents':df.index, 'values':df.values})
 I get,
 Exception: Data must be 1-dimensional

Solution

  • Use reset_index with rename_axis for new column name:

    filter_df = df.rename_axis('content').reset_index()
    

    Another solution with rename:

    filter_df = df.reset_index().rename(columns={'index':'content'})
    

    For DataFrame from constructor need df['primary'] for select column

    filter_df=pd.DataFrame({'contents':df.index, 'values':df['primary'].values})
    

    print (filter_df)
          content  primary
    0         Buy      484
    1        Sell      429
    2      Blanks      130
    3     FX Spot      108
    4      Income       77
    5  FX Forward        2