Home » Python » python – Adding columns one by one to a new DataFrame-Exceptionshub

python – Adding columns one by one to a new DataFrame-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

For a new pandas DataFrame:

In [3]:    import pandas as pd
           dfo = pd.DataFrame() 
   ...:    dfo['filename'] = 'file1.csv'                                                                                                                                                

What are its columns?

In [4]: dfo.columns                                                                                                                                                                     
Out[4]: Index(['filename'], dtype='object')

That looks OK. What about the “row” that was added (with value file1.csv) ?

In [5]: len(dfo)                                                                                                                                                                        
Out[5]: 0

Not so good.. So what happened here? How should that column value be added: can it be done similarly to the original attempt or do we need separate commands?

My motivation is that the set of columns is determined dynamically and it fits this particular use case better to do one at a time instead of in bulk like I typically do.

How to&Answers:

The input should be a list

import pandas as pd
df = pd.DataFrame()
df['filename'] = ['hhh.xlsx']

and the dataframe will be

In[1]:print(len(df))
Out[1]:1

Is this what you want?