pandas dataframe转list、set、dict

刘超 18天前 ⋅ 1145 阅读   编辑

一、输入多维dataframe

  1、转为字典dict

>>> import pandas as pd
>>> df1 = pd.DataFrame([['Snow','M',22],['Tyrion','M',32],['Sansa','F',18],['Arya','F',14]], columns=['name','gender','age'])
>>> df1.to_dict()
{'gender': {0: 'M', 1: 'M', 2: 'F', 3: 'F'}, 'age': {0: 22, 1: 32, 2: 18, 3: 14}, 'name': {0: 'Snow', 1: 'Tyrion', 2: 'Sansa', 3: 'Arya'}}
>>> df1.to_dict().values()
[{0: 'M', 1: 'M', 2: 'F', 3: 'F'}, {0: 22, 1: 32, 2: 18, 3: 14}, {0: 'Snow', 1: 'Tyrion', 2: 'Sansa', 3: 'Arya'}]

  2、转换列表list

>>> df1.values.tolist()
[['Snow', 'M', 22], ['Tyrion', 'M', 32], ['Sansa', 'F', 18], ['Arya', 'F', 14]]
>>> df1.to_records().tolist()
[(0, 'Snow', 'M', 22), (1, 'Tyrion', 'M', 32), (2, 'Sansa', 'F', 18), (3, 'Arya', 'F', 14)]
# 把name列的元素转换成list:
# 方法1
>>> df1['name'].values.tolist()
['Snow', 'Tyrion', 'Sansa', 'Arya']
# 方法2
>>> df1['name'].tolist()
['Snow', 'Tyrion', 'Sansa', 'Arya']

  3、转换set

# 把name列中不重复的元素转换成list(也可以说是set):
>>> df1['name'].drop_duplicates().values.tolist()
['Snow', 'Tyrion', 'Sansa', 'Arya']

二、输入一维dataframe

df = pd.DataFrame([3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9])
# 转换成list[list]:
>>> df.values.tolist()
[[3], [5], [6], [2], [4], [6], [7], [8], [7], [8], [9]]


注意:本文归作者所有,未经作者允许,不得转载

全部评论: 0

    我有话说: