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
Yes it is possible to create any shape dataframe.
You can add rows to the pandas dataframe using df. iLOC[i] = ['col-1-value', 'col-2-value', ' col-3-value '] statement.
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.
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
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}])
#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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With