为了账号安全,请及时绑定邮箱和手机立即绑定

从熊猫数据框列获取列表

从熊猫数据框列获取列表

慕桂英3389331 2019-10-15 13:54:46
我有一个看起来像这样的Excel文档。cluster load_date   budget  actual  fixed_priceA   1/1/2014    1000    4000    YA   2/1/2014    12000   10000   YA   3/1/2014    36000   2000    YB   4/1/2014    15000   10000   NB   4/1/2014    12000   11500   NB   4/1/2014    90000   11000   NC   7/1/2014    22000   18000   NC   8/1/2014    30000   28960   NC   9/1/2014    53000   51200   N我希望能够将列1的内容-群集作为列表返回,因此我可以对其运行一个for循环,并为每个群集创建一个excel工作表。还可以将整行的内容返回到列表吗?例如list = [], list[column1] or list[df.ix(row1)]
查看完整描述

3 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

当您将Pandas DataFrame列拉出时,它们就是Pandas Series,然后您可以调用x.tolist()它们以将其转换为Python列表。或者,您也可以使用list(x)。


import pandas as pd


d = {'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(d)


print("Starting with this dataframe\n", df)


print("The first column is a", type(df['one']), "\nconsisting of\n", df['one'])


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


dfList = list(df['one'])


dfValues = df['one'].values


print("dfToList is", dfToList, "and it's a", type(dfToList))

print("dfList is  ", dfList,   "and it's a", type(dfList))

print("dfValues is", dfValues, "and it's a", type(dfValues))

最后几行返回:


dfToList is [1.0, 2.0, 3.0, nan] and it's a <class 'list'>

dfList is   [1.0, 2.0, 3.0, nan] and it's a <class 'list'>

dfValues is [ 1.  2.  3. nan] and it's a <class 'numpy.ndarray'>

这个问题可能会有所帮助。一旦您了解了Pandas的风格,它们实际上就是相当不错的。


因此,您可以:


my_list = df["cluster"].tolist()


然后从那里去。


查看完整回答
反对 回复 2019-10-15
?
慕的地10843

TA贡献1785条经验 获得超8个赞

这将返回一个numpy数组:


my_list = df["cluster"].values

这将返回一个numpy数组,用于唯一值:


my_list = df["cluster"].values

uniqueVals = np.unique(my_list)

或者:


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


查看完整回答
反对 回复 2019-10-15
?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

转换示例:

numpy数组->熊猫数据框->熊猫列中的列表


numpy数组


data = np.array([[10,20,30], [20,30,60], [30,60,90]])

将numpy数组转换为熊猫框架


data = np.array([[10,20,30], [20,30,60], [30,60,90]])

dataPd = pd.DataFrame(data = data)


print(dataPd)

    0   1   2

0  10  20  30

1  20  30  60

2  30  60  90

转换一个熊猫框到列表

pdToList = list(dataPd['2'])


遍历列表作为证明


 for counter, value in enumerate(pdToList):

        print(counter, value)

    0 90

    1 60

    2 30


查看完整回答
反对 回复 2019-10-15
  • 3 回答
  • 0 关注
  • 536 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信