import pandas as pd datas = [[65,92,78,83,70], [90,72,76,93,56], [81,85,91,89,77], [79,53,47,94,80]] indexs = ["林大明", "陈聪明", "黄美丽", "熊小娟"] columns = ["语文", "数学", "英文", "自然", "社会"] df = pd.DataFrame(datas, columns=columns, index=indexs) print(df)
DataFrame 数据的修改
修改 DataFrame 数据的操作非常简单,只需要把读取的数据项设为指定
值即可。例如,把陈聪明的数学成绩修改为 91 :
import pandas as pd datas = [[65,92,78,83,70], [90,72,76,93,56], [81,85,91,89,77], [79,53,47,94,80]] indexs = ["林大明", "陈聪明", "黄美丽", "熊小娟"] columns = ["语文", "数学", "英文", "自然", "社会"] df = pd.DataFrame(datas, columns=columns, index=indexs) print('df.ix["陈聪明"]["数学"] (原始):' + str(df.loc["陈聪明"]["数学"])) df.ix["陈聪明"]["数学"] = 91 print('df.ix["陈聪明"]["数学"] (修改):' + str(df.loc["陈聪明"]["数学"]))
或把陈聪明的所有成绩都改为 80:
df.ix["陈聪明", :] = 80 print(df.ix["陈聪明", :])
DataFrame 数据的排序
Pandas 提供了两种 DataFrame 数据排序功能 。
第 l 种排序功能是根据指定列标题下的值进行排序,语法为 :
例如,根据数学成绩做降序排序,井把结果存入 dfl 中:
import pandas as pd datas = [[65,92,78,83,70], [90,72,76,93,56], [81,85,91,89,77], [79,53,47,94,80]] indexs = ["林大明", "陈聪明", "黄美丽", "熊小娟"] columns = ["语文", "数学", "英文", "自然", "社会"] df = pd.DataFrame(datas, columns=columns, index=indexs) print('按照数学成绩降序排序 ->') df1 = df.sort_values(by="数学", ascending=False) print(df1)
第 2 种排序功能是根据行标题或列标题进行排序,语法为 :
print('按照列标题升序排序 ->') df2 = df.sort_index(axis=0) print(df2)