参考:
(3条消息)pandas中的DataFrame按指定顺序输出所有列 - quintind的专栏 - CSDN博客
https://blog.csdn.net/quintind/article/details/79691574
(1)创建数据框:
import pandas as pd
grades = [48,99,75,80,42,80,72,68,36,78]
df = pd.DataFrame( {'ID': ["x%d" % r for r in range(10)],
'Gender' : ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'M'],
'ExamYear': ['2007','2007','2007','2008','2008','2008','2008','2009','2009','2009'],
'Class': ['algebra', 'stats', 'bio', 'algebra', 'algebra', 'stats', 'stats', 'algebra', 'bio', 'bio'],
'Participated': ['yes','yes','yes','yes','no','yes','yes','yes','yes','yes'],
'Passed': ['yes' if x > 50 else 'no' for x in grades],
'Employed': [True,True,True,False,False,False,False,True,True,False],
'Grade': grades})
print(df)
输出:
(2)整理按指定列输出
代码:
col = ['Grade','Passed','ID','Class','Gender','Participated','Employed','ExamYear']
df=df.ix[:,cols]
输出:
(3) 数据框转化成列表
方法一:
借助数组
import numpy as np
df = np.arrary(df)
df1 = df.tolist()
方法二:
df1 = (df.values).tolist()
输出结果:
(4)数据框中某一列的值转化为字符串
df2 = (df.values).tostring()
df3 = (df['ID'].values).tostring()
输出:
不懂为啥是这个样子
希望的样子:
代码:
df4 = tuple(df['ID'])
df5 = str(df4)
输出: