Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 953
EHB Avatar asked Apr 01 '18 21:04

EHB


People also ask

How do I get a row of A pandas DataFrame?

To get the nth row in a Pandas DataFrame, we can use the iloc() method. For example, df. iloc[4] will return the 5th row because row numbers start from 0.


2 Answers

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
 
like image 142
cs95 Avatar answered Oct 23 '22 03:10

cs95


Notice , you should follow what cold and jpp's construction for creating the one row dataframe, but here I am try to fix your code. change DataFrame call to

pd.Series([a,b,c], index=list('abc')).to_frame(0).T
Out[15]: 
   a  b  c
0  1  2  3
like image 7
BENY Avatar answered Oct 23 '22 03:10

BENY