Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 571
uzan jap Avatar asked Oct 15 '25 18:10

uzan jap


2 Answers

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
like image 155
Black Raven Avatar answered Oct 17 '25 06:10

Black Raven


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

df['new'] = 0
like image 36
Usama Aleem Avatar answered Oct 17 '25 06:10

Usama Aleem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!