3 回答
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()
然后从那里去。
TA贡献1785条经验 获得超8个赞
这将返回一个numpy数组:
my_list = df["cluster"].values
这将返回一个numpy数组,用于唯一值:
my_list = df["cluster"].values
uniqueVals = np.unique(my_list)
或者:
uniqueVals = df["cluster"].unique()
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
添加回答
举报