从熊猫数据框列获取列表

我有一个看起来像这样的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的内容-群集作为列表返回,因此我可以对其运行一个for循环,并为每个群集创建一个excel工作表。


还可以将整行的内容返回到列表吗?例如


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


慕桂英3389331
浏览 538回答 3
3回答

慕容3067478

当您将Pandas DataFrame列拉出时,它们就是Pandas Series,然后您可以调用x.tolist()它们以将其转换为Python列表。或者,您也可以使用list(x)。import pandas as pdd = {'one' : pd.Series([1., 2., 3.],&nbsp; &nbsp; &nbsp;index=['a', 'b', 'c']),&nbsp; &nbsp; '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'].valuesprint("dfToList is", dfToList, "and it's a", type(dfToList))print("dfList is&nbsp; ", dfList,&nbsp; &nbsp;"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&nbsp; &nbsp;[1.0, 2.0, 3.0, nan] and it's a <class 'list'>dfValues is [ 1.&nbsp; 2.&nbsp; 3. nan] and it's a <class 'numpy.ndarray'>这个问题可能会有所帮助。一旦您了解了Pandas的风格,它们实际上就是相当不错的。因此,您可以:my_list = df["cluster"].tolist()然后从那里去。

慕的地10843

这将返回一个numpy数组:my_list = df["cluster"].values这将返回一个numpy数组,用于唯一值:my_list = df["cluster"].valuesuniqueVals = np.unique(my_list)或者:uniqueVals = df["cluster"].unique()

吃鸡游戏

转换示例: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)&nbsp; &nbsp; 0&nbsp; &nbsp;1&nbsp; &nbsp;20&nbsp; 10&nbsp; 20&nbsp; 301&nbsp; 20&nbsp; 30&nbsp; 602&nbsp; 30&nbsp; 60&nbsp; 90转换一个熊猫框到列表pdToList = list(dataPd['2'])遍历列表作为证明&nbsp;for counter, value in enumerate(pdToList):&nbsp; &nbsp; &nbsp; &nbsp; print(counter, value)&nbsp; &nbsp; 0 90&nbsp; &nbsp; 1 60&nbsp; &nbsp; 2 30
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python