将 Pandas DataFrame 列转换为列表
本教程文章将介绍不同的方法将 Pandas DataFrame 列转换为列表,比如使用 Pandas 中的 tolist()
方法。
使用 tolist()
方法将 Dataframe 列转换为列表
Pandas DataFrame 中的一列就是一个 Pandas Series
。因此,如果我们需要将一列转换为一个列表,我们可以使用 Series
中的 tolist()
方法。
在下面的代码中,df['DOB']
从 DataFrame 中返回名称为 DOB
的 Series
或列。
tolist()
方法将 Series
转换为一个列表。
import pandas as pd
df=pd.DataFrame([
['James', '1/1/2014', '1000'],
['Michelina', '2/1/2014', '12000'],
['Marc', '3/1/2014', '36000'],
['Bob', '4/1/2014', '15000'],
['Halena', '4/1/2014', '12000']
], columns=['Name', 'DOB','Salary'])
print("Pandas DataFrame:\n\n",df,"\n")
list_of_single_column = df['DOB'].tolist()
print("the list of a single column from the dataframe\n",
list_of_single_column,
"\n",
type(list_of_single_column))
输出:
Pandas DataFrame:
Name DOB Salary
0 James 1/1/2014 1000
1 Michelina 2/1/2014 12000
2 Marc 3/1/2014 36000
3 Bob 4/1/2014 15000
4 Halena 4/1/2014 12000
the list of a single column from the dataframe
['1/1/2014', '2/1/2014', '3/1/2014', '4/1/2014', '4/1/2014']
<class 'list'>
使用 list()
函数将 DataFrame 中的列转换为列表
我们也可以使用 list()
函数将 DataFrame 传递给 list()
函数来将 DataFrame 列转换为列表。
我们将使用与上面相同的数据来演示这种方法。
import pandas as pd
df=pd.DataFrame([
['James', '1/1/2014', '1000'],
['Michelina', '2/1/2014', '12000'],
['Marc', '3/1/2014', '36000'],
['Bob', '4/1/2014', '15000'],
['Halena', '4/1/2014', '12000']
], columns=['Name', 'DOB','Salary'])
print("Pandas DataFrame:\n\n",df,"\n")
list_of_single_column = list(df['DOB'])
print("the list of a single column from the dataframe\n",
list_of_single_column,
"\n",
type(list_of_single_column))
输出:
Pandas DataFrame:
Name DOB Salary
0 James 1/1/2014 1000
1 Michelina 2/1/2014 12000
2 Marc 3/1/2014 36000
3 Bob 4/1/2014 15000
4 Halena 4/1/2014 12000
the list of a single column from the dataframe
['1/1/2014', '2/1/2014', '3/1/2014', '4/1/2014', '4/1/2014']
<class 'list'>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。