Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Using variables to create dataframe with one row and column names from variable names

Suppose I have some variables in Python. I am trying to create a 1-row Pandas dataframe, where the column names are the variables' names and the values in the row are from the variables.

For example, if I have this code:

pi  = 3.142
e   = 2.718
phi = 1.618

I would like a dataframe that conceptually looks like this:

     pi     e      phi
0   3.142   2.718  1.618

I tried the following, but everything is in one column, and the variable names are not added:

df = pd.DataFrame(data=[pi, e, phi])
df
#        0
# 0  3.140
# 1  2.718
# 2  1.618

Note that I'm trying to replicate the behavior of some of my older R code.

pi  <- 3.142
e   <- 2.718
phi <- 1.618
df  <- data.frame(pi, e, phi)
df
#      pi     e   phi
# 1 3.142 2.718 1.618
like image 500
stackoverflowuser2010 Avatar asked May 22 '17 17:05

stackoverflowuser2010


People also ask

Can we create a data frame having any number of rows and columns?

Yes it is possible to create any shape dataframe.

How do you create rows and columns in pandas?

You can add rows to the pandas dataframe using df. iLOC[i] = ['col-1-value', 'col-2-value', ' col-3-value '] statement.

How do I assign a value to a row and column in pandas?

You can set cell value of pandas dataframe using df.at[row_label, column_label] = 'Cell Value'. It is the fastest method to set the value of the cell of the pandas dataframe. Dataframe at property of the dataframe allows you to access the single value of the row/column pair using the row and column labels.


Video Answer


3 Answers

I think you were looking for this format:

pd.DataFrame([[pi,e,phi]],columns=['pi','e','phi'])

Output:

      pi      e    phi
0  3.142  2.718  1.618
like image 53
Scott Boston Avatar answered Oct 08 '22 09:10

Scott Boston


You can use a list and dictionary like this

df = pd.DataFrame([{'pi':pi, 'e':e, 'phi':phi}])

which returns

df
Out[5]: 
       e    phi     pi
0  2.718  1.618  3.142

to preserve the column order, you can use the columns argument:

df = pd.DataFrame([{'pi':pi, 'e':e, 'phi':phi}], columns=['pi', 'e', 'phi'])

which returns

df
Out[9]: 
      pi      e    phi
0  3.142  2.718  1.618

Additional rows would go into separate dictionaries like this:

df = pd.DataFrame([{'pi':pi, 'e':e, 'phi':phi}, {'pi':2, 'e':3, 'phi':1}])
like image 35
lmo Avatar answered Oct 08 '22 07:10

lmo


#Reference columns names only once and column order is retained.    
pd.concat([pd.DataFrame(data=[eval(k)],columns=[k]) for k in ['pi','e','phi']],axis=1)
Out[1226]: 
      pi      e    phi
0  3.142  2.718  1.618
like image 2
Allen Avatar answered Oct 08 '22 09:10

Allen