从 Pandas 数据框列或行获取列表? [英] Get list from pandas dataframe column or row?

查看:37
本文介绍了从 Pandas 数据框列或行获取列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从 Excel 文档导入的数据框 df,如下所示:

I have a dataframe df imported from an Excel document like this:

cluster load_date   budget  actual  fixed_price
A   1/1/2014    1000    4000    Y
A   2/1/2014    12000   10000   Y
A   3/1/2014    36000   2000    Y
B   4/1/2014    15000   10000   N
B   4/1/2014    12000   11500   N
B   4/1/2014    90000   11000   N
C   7/1/2014    22000   18000   N
C   8/1/2014    30000   28960   N
C   9/1/2014    53000   51200   N

我希望能够将第 1 列 df['cluster'] 的内容作为列表返回,以便我可以对其运行 for 循环,并为每个创建一个 Excel 工作表集群.

I want to be able to return the contents of column 1 df['cluster'] as a list, so I can run a for-loop over it, and create an Excel worksheet for every cluster.

是否也可以将整列或整行的内容返回到列表中?例如

Is it also possible to return the contents of a whole column or row to a list? e.g.

list = [], list[column1] or list[df.ix(row1)]

推荐答案

Pandas DataFrame 列在拉出时就是 Pandas 系列,然后可以调用 x.tolist() 打开它们进入 Python 列表.或者,您可以使用 list(x) 进行转换.

Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist() on to turn them into a Python list. Alternatively you cast it with list(x).

import pandas as pd

data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
             'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_dict)

print(f"DataFrame:
{df}
")
print(f"column types:
{df.dtypes}")

col_one_list = df['one'].tolist()

col_one_arr = df['one'].to_numpy()

print(f"
col_one_list:
{col_one_list}
type:{type(col_one_list)}")
print(f"
col_one_arr:
{col_one_arr}
type:{type(col_one_arr)}")

输出:

DataFrame:
   one  two
a  1.0    1
b  2.0    2
c  3.0    3
d  NaN    4

column types:
one    float64
two      int64
dtype: object

col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>

col_one_arr:
[ 1.  2.  3. nan]
type:<class 'numpy.ndarray'>

这篇关于从 Pandas 数据框列或行获取列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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