Home > Mobile >  List of values as columns in Dataframe
List of values as columns in Dataframe

Time:03-04

I'm trying to create a data frame in which column names should come from list in python. For eg:- list=['6567565','67578','Speed','distance','allowance'] then data frame:-

6567565 67578 Speed distance allowance**
0 0 0 0 0

Initial values would be 0 for every column

CodePudding user response:

You pass in an argument for the column names when you create the data frame object.

>>> import pandas as pd
>>> data = [[0]*5]
>>> data
[[0, 0, 0, 0, 0]]
>>> df = pd.DataFrame(data, columns=['6567565', '67578', 'Speed', 'distance', 'allowance'])
>>> df
   6567565  67578  Speed  distance  allowance
0        0      0      0         0          0

CodePudding user response:

Creat the dataframe then fillna

out = pd.DataFrame(columns=l,index=[0]).fillna(0)
Out[484]: 
   6567565  67578  Speed  distance  allowance
0        0      0      0         0          0

CodePudding user response:

Just add the list of column names when making an empty dataframe.

import pandas as pd

# empty df
df = pd.DataFrame()

Empty DataFrame
Columns: []
Index: []


# col names
names=['6567565','67578','Speed','distance','allowance']

# empty df but with column names
df = pd.DataFrame(columns = names)

Empty DataFrame
Columns: [6567565, 67578, Speed, distance, allowance]
Index: []


# populating first row with zeros
df.loc[len(df)] = 0

  6567565 67578 Speed distance allowance
0       0     0     0        0         0


# or just creating a dataframe with a row of zeros in one line
import numpy as np
df = pd.DataFrame(np.zeros((1, 5)), columns = names) # 1 row, 5 columns

   6567565  67578  Speed  distance  allowance
0      0.0    0.0    0.0       0.0        0.0
  • Related