Home > Software engineering >  Initialize dataframe with two columns which have one of the them all zeros
Initialize dataframe with two columns which have one of the them all zeros

Time:07-26

I have a list and I want to convert it to a dataframe. In the second column, I want to give all zeros but I got "object of type 'int' has no len()" error. The thing I did is this:

df = pd.DataFrame([all_equal_timestamps['A'], 0],  columns=['data','label'])

How can i add second column with all zeros to this dataframe in the easiest manner and why did the code above give me this error?

CodePudding user response:

you can add a column named as "new" with all zero by using

df['new'] = 0

CodePudding user response:

You can do it all in one line with assign:

timestamps = [1,0,3,5]

pd.DataFrame({"Data":timestamps}).assign(new=0)

Output:


   Data new
0   1   0
1   0   0
2   3   0
3   5   0

CodePudding user response:

Not sure what is in all_equal_timestamps, so I presume it's a list of elements. Do you mean to get this result?

import pandas as pd

all_equal_timestamps = {'A': ['1234', 'aaa', 'asdf']}
df = pd.DataFrame(all_equal_timestamps['A'],  columns=['data']).assign(label=0)
# df['label'] = 0
print(df)

Output:

   data  label
0  1234      0
1   aaa      0
2  asdf      0

If you're creating a DataFrame with a list of lists, you'd expect something like this

df = pd.DataFrame([ all_equal_timestamps['A'], '0'*len(all_equal_timestamps['A']) ],  columns=['data', 'label', 'anothercol'])
print(df)

Output:

   data label anothercol
0  1234   aaa       asdf
1     0     0          0
  • Related