Search code examples
pythonpandasdataframenaming

Make One-Row Dataframe


I'm unable to construct a dataframe from 3 individual numbers. I want to do this in order for a function to return the dataframe, which I then append to other existing results.

Desired result is a dataframe with columns named "a", "b" and "C", each containing the value of a, b, and c.

Try one:

a=1
b=2
c=3
dat=pd.DataFrame([a,b,c], columns=list('abc')) #fails with size error

Try two:

dat=pd.DataFrame()
dat['a']=pd.np.nan
dat['b']=pd.np.nan
dat['c']=pd.np.nan

dat['c']=c # no numbers are added to the column; still has 0 rows

What am I missing here?

Desired result is:

    a  | b  | c
   -------------
    1  | 2  | 3

Solution

  • pd.DataFrame([[a, b, c]], columns=['a', 'b', 'c'])
    
       a  b  c
    0  1  2  3
    

    Note that your "bonus ask" isn't really possible, because an object may be associated with multiple variables (think about it).

    You may, however, consider using a dictionary.

    data = {'a' : 1, 'b' : 2, 'c' : 3}
    pd.DataFrame(data, index=[0])  # the `index` argument is important 
    
       a  b  c
    0  1  2  3