Home > Back-end >  How to initialize a pandas dataframe with empty lists
How to initialize a pandas dataframe with empty lists

Time:10-08

I want to achieve the following as an example:

ix A B
0 [] []
1 [] []

CodePudding user response:

According to pandas documentation, you can make a dataframe by passing a dictionary in the shape {'Column' : ['values']}. In this case:

import pandas as pd

data = {'A': [[], []], 'B': [[], []]}
df = pd.DataFrame(data=data)

print(df)
#    A   B
# 0  []  []
# 1  []  []

CodePudding user response:

If you want to do this programmatically, you could use:

idx  = [0,1]
cols = ['A', 'B']
df = pd.DataFrame([[[] for i in range(len(cols))] for i in range(len(idx))],
                  index=idx, columns=cols,
                 )

output:

    A   B
0  []  []
1  []  []

Or you could cheat a bit and take advantage of pandas str methods:

df = (pd.DataFrame('', index=idx, columns=cols)
        .apply(lambda c: c.str.split())
     )

output:

    A   B
0  []  []
1  []  []
  • Related