Home > Net >  Add name to dataframe pandas
Add name to dataframe pandas

Time:04-17

I am having data frame as follows:

Date        Description Amount
12/01/2019  ABC         51,026
13/01/2019  XYZ         12,111.56

I want to add a single name field to the whole data frame having 3 columns "Date Description and Amount" and want to get the output as follows:

 Name: Shivam
 Date        Description Amount
 12/01/2019  ABC         51,026
 13/01/2019  XYZ         12,111.56

I have tried adding a dictionary of name to one data frame and "Date Description and Amount" to another Data Frame and merged both. But it is creating another column of name along with "Date Description and Amount". But I want name to be only one time and not the whole column.

Please suggest some ways to do this.

CodePudding user response:

You can use the metadata to add raw attributes.

import pandas as pd

class metadatadf(pd.DataFrame):

    _metadata = ['metadata']

    @property
    def _constructor(self):
        return metadatadf

data = {"Data": ['12/01/2019', " 13/01/2019"], "Description": ['ABC', 'XYZ'] ,"Amount":['51,026','12,111.56']}
df = metadatadf(data)
df.metadata = " Name:Shivam"
print(df.head().metadata)
print(df)

Th output:

 Name:Shivam
          Data Description     Amount
0   12/01/2019         ABC     51,026
1   13/01/2019         XYZ  12,111.56

CodePudding user response:

I believe this is one way to do what your question describes:

import pandas as pd
mi = pd.MultiIndex.from_product([['Name: Shivam'], 'Date,Description,Amount'.split(',')])
print(mi)
df = pd.DataFrame([['12/01/2019', 'ABC', 51026], ['13/01/2019', 'XYZ', 12111.56]], columns=mi)
print(df)

Output:

MultiIndex([('Name: Shivam',        'Date'),
            ('Name: Shivam', 'Description'),
            ('Name: Shivam',      'Amount')],
           )
  Name: Shivam
          Date Description    Amount
0   12/01/2019         ABC  51026.00
1   13/01/2019         XYZ  12111.56
  • Related