Initialize dataframe with two columns which have one of the them all zeros

Question:

I have a list and I would like to convert it to a pandas 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?

Asked By: uzan jap

||

Answers:

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

df['new'] = 0
Answered By: Usama Aleem

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
Answered By: perpetualstudent

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
Answered By: Michael S.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.