pandas 将二维 numpy 数组转换为数据帧行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45962548/
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 04:21:03  来源:igfitidea点击:

Converting a 2D numpy array to dataframe rows

pythonpandasnumpydataframe

提问by i.n.n.m

I have a list of list that I would like to make it as a row. The closest I got was using this post. However, I could not get my answer.

我有一个列表列表,我想把它排成一行。我得到的最接近的是使用这篇文章。但是,我无法得到我的答案。

For example lets say I have a testarrayof values,

例如,假设我有一个testarray值,

([[ 26.85406494], 
   [ 27.85406494],
   [ 28.85406494],
   [ 29.85406494],
   [ 30.85406494],
   [ 31.85406494],
   [ 32.85406494],
   [ 33.85406494],
   [ 34.85406494],
   [ 35.85406494],
   [ 36.85406494],
   [ 37.85406494],
   [ 38.85406494],
   [ 39.85406494],
   [ 40.85406494],
   [ 41.85406494]])

I need like as a pandasDataFrame row like this,

我需要像这样的pandasDataFrame 行,

  Row_value
0 26.85406494
1 27.85406494
2 29.85406494
...

I tried the following,

我尝试了以下,

df = pd.DataFrame({'Row_value':testarray})

I get an error,

我收到一个错误,

ValueError: If using all scalar values, you must pass an index

ValueError:如果使用所有标量值,则必须传递索引

How can I pass those values with an index?

如何通过索引传递这些值?

回答by jezrael

Use DataFrame constructor only with parameter columns:

仅对参数列使用 DataFrame 构造函数:

df = pd.DataFrame(a, columns=['a'])
print (df)
            a
0   26.854065
1   27.854065
2   28.854065
3   29.854065
4   30.854065
5   31.854065
6   32.854065
7   33.854065
8   34.854065
9   35.854065
10  36.854065
11  37.854065
12  38.854065
13  39.854065
14  40.854065
15  41.854065

回答by cs95

Try a .reshape(-1, ):

尝试一个.reshape(-1, )

df = pd.DataFrame({'Row_value':testarray.reshape(-1, )})
df

    Row_value
0   26.854065
1   27.854065
2   28.854065
3   29.854065
4   30.854065
5   31.854065
6   32.854065
7   33.854065
8   34.854065
9   35.854065
10  36.854065
11  37.854065
12  38.854065
13  39.854065
14  40.854065
15  41.854065

It looks like your testarrayis a 2D array with 1 column. Convert it to a 1D array.

看起来你testarray是一个 1 列的二维数组。将其转换为一维数组。



The alternative is to not pass a dictionary, but instead pass testarrayas is, like in jezrael's answer.

另一种方法是不传递字典,而是testarray按原样传递,就像在 jezrael 的回答中一样。