将列表读入pandas DataFrame的列 [英] Read lists into columns of pandas DataFrame

查看:182
本文介绍了将列表读入pandas DataFrame的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表加载到pandas DataFrame的列中,但似乎不能简单地做到这一点.这是我要使用transpose()的示例,但我认为这是不必要的:

I want to load lists into columns of a pandas DataFrame but cannot seem to do this simply. This is an example of what I want using transpose() but I would think that is unnecessary:

In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: x = np.linspace(0,np.pi,10)
In [4]: y = np.sin(x)
In [5]: data = pd.DataFrame(data=[x,y]).transpose()
In [6]: data.columns = ['x', 'sin(x)']
In [7]: data
Out[7]: 
          x        sin(x)
0  0.000000  0.000000e+00
1  0.349066  3.420201e-01
2  0.698132  6.427876e-01
3  1.047198  8.660254e-01
4  1.396263  9.848078e-01
5  1.745329  9.848078e-01
6  2.094395  8.660254e-01
7  2.443461  6.427876e-01
8  2.792527  3.420201e-01
9  3.141593  1.224647e-16

[10 rows x 2 columns]

在创建DataFrame时,是否可以将每个列表直接加载到列中以消除转置并插入列标签?

Is there a way to directly load each list into a column to eliminate the transpose and insert the column labels when creating the DataFrame?

推荐答案

有人刚刚建议根据数据创建一个字典,然后像这样将其加载到DataFrame中:

Someone just recommended creating a dictionary from the data then loading that into the DataFrame like this:

In [8]: data = pd.DataFrame({'x': x, 'sin(x)': y})
In [9]: data
Out[9]: 
          x        sin(x)
0  0.000000  0.000000e+00
1  0.349066  3.420201e-01
2  0.698132  6.427876e-01
3  1.047198  8.660254e-01
4  1.396263  9.848078e-01
5  1.745329  9.848078e-01
6  2.094395  8.660254e-01
7  2.443461  6.427876e-01
8  2.792527  3.420201e-01
9  3.141593  1.224647e-16

[10 rows x 2 columns]

请注意,字典是键值对的无序集合.如果您关心列的顺序,则应传递要使用的有序键值的列表(也可以使用此列表仅包括某些dict条目):

Note than a dictionary is an unordered set of key-value pairs. If you care about the column orders, you should pass a list of the ordered key values to be used (you can also use this list to only include some of the dict entries):

data = pd.DataFrame({'x': x, 'sin(x)': y}, columns=['x', 'sin(x)'])

这篇关于将列表读入pandas DataFrame的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆