pandas 将 python 列表附加到 DataFrame 列

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

Append python lists to DataFrame columns

python-3.xpandasdataframe

提问by user7852656

I have multiple python lists. But I want to collect each list into Dataframe columns.

我有多个 python 列表。但我想将每个列表收集到 Dataframe 列中。

new_list=pd.DataFrame([])

for i in range(0,4):
    new_list.append(my_list[i])

Then I get an error message, TypeError: cannot concatenate object of type "<class 'numpy.ndarray'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid.

然后我收到一条错误消息, TypeError: cannot concatenate object of type "<class 'numpy.ndarray'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid.

my_list=([3.50913843e-05,1.64190123e-04, 4.19101449e-04, 4.40226697e-04, 3.11362684e-04],[4.573843e-05,6.795123e-04, 3.219e-04, 1.557897e-04, 3.11362684e-04], [7.0543e-05,1.64190123e-04, 2.154e-04, 4.40226697e-04, 3.11362684e-04])

The outcome I want is

我想要的结果是

3.50913843e-05     4.573843e-05     7.0543e-05
1.64190123e-04     6.795123e-04     1.64190123e-04
4.19101449e-04     3.219e-04     2.154e-04
4.40226697e-04     1.557897e-04     4.40226697e-04
3.11362684e-04     3.11362684e-04     3.11362684e-04

Any idea what is going wrong and how I could fix it?

知道出了什么问题,我该如何解决?

回答by YOBEN_S

So using

所以使用

pd.DataFrame(np.array(my_list).T)
Out[929]: 
          0         1         2
0  0.000035  0.000046  0.000071
1  0.000164  0.000680  0.000164
2  0.000419  0.000322  0.000215
3  0.000440  0.000156  0.000440
4  0.000311  0.000311  0.000311

回答by cs95

You don't have to iteratively build a DataFrame - just pass it in at once. Either, pass a list-of-lists and transpose:

您不必反复构建 DataFrame - 只需一次传入即可。或者,传递一个列表列表并转置:

pd.DataFrame(list(my_list)).T

          0         1         2
0  0.000035  0.000046  0.000071
1  0.000164  0.000680  0.000164
2  0.000419  0.000322  0.000215
3  0.000440  0.000156  0.000440
4  0.000311  0.000311  0.000311

Or, inverse-zip, without the transposition.

或者, inverse- zip,没有换位。

pd.DataFrame(list(zip(*my_list)))

          0         1         2
0  0.000035  0.000046  0.000071
1  0.000164  0.000680  0.000164
2  0.000419  0.000322  0.000215
3  0.000440  0.000156  0.000440
4  0.000311  0.000311  0.000311