我有一个dataframe df从一个Excel文档导入,就像这样:

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工作表。

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

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

当前回答

如果你想使用索引而不是列名(例如在循环中),你可以使用

for i in range(len(df.columns)):
    print(df[df.columns[i]].to_list())

其他回答

当您将Pandas DataFrame列取出时,它们就是Pandas Series,然后您可以调用x.tolist()将它们转换为Python列表。或者使用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:\n{df}\n")
print(f"column types:\n{df.dtypes}")

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

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

print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{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'>
 amount = list()
    for col in df.columns:
        val = list(df[col])
        for v in val:
            amount.append(v)

下面是简单的一行代码:

load_date’(df)名单

更新:toList()不起作用。它应该是小写的。tolist()

假设读取excel表格后的dataframe的名称是df,取一个空列表(例如dataList),逐行迭代dataframe,并像-一样添加到空列表中

dataList = [] #empty list
for index, row in df.iterrows(): 
    mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
    dataList.append(mylist)

Or,

dataList = [] #empty list
for row in df.itertuples(): 
    mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
    dataList.append(mylist)

不,如果你打印dataList,你会得到每一行作为一个列表在dataList。

返回一个numpy数组:

arr = df["cluster"].to_numpy()

返回唯一值的numpy数组:

unique_arr = df["cluster"].unique()

你也可以使用numpy来获取唯一的值,尽管这两种方法之间存在差异:

arr = df["cluster"].to_numpy()
unique_arr = np.unique(arr)