Pandas:使用变量从变量名称创建具有一行名称和列名称的数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44118416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:40:06  来源:igfitidea点击:

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

pythonrpandasdataframe

提问by stackoverflowuser2010

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.

假设我在 Python 中有一些变量。我正在尝试创建一个 1 行的 Pandas 数据框,其中列名是变量的名称,行中的值来自变量。

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.

请注意,我正在尝试复制一些旧 R 代码的行为。

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

采纳答案by Scott Boston

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

回答by Allen

#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

回答by lmo

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:

要保留列顺序,您可以使用 columns 参数:

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}])