pandas DataFrame的建立方法

pandas DataFrame的增删查改总结系列文章:html

在pandas里,DataFrame是最常常用的数据结构,这里总结生成和添加数据的方法:
①、把其余格式的数据整理到DataFrame中;
②在已有的DataFrame中插入N列或者N行。python

1. 字典类型读取到DataFrame(dict to DataFrame)

假如咱们在作实验的时候获得的数据是dict类型,为了方便以后的数据统计和计算,咱们想把它转换为DataFrame,存在不少写法,这里简单介绍经常使用的几种:
方法一:直接使用pd.DataFrame(data=test_dict)便可,括号中的data=写不写均可以,具体以下:git

test_dict = {'id':[1,2,3,4,5,6],'name':['Alice','Bob','Cindy','Eric','Helen','Grace '],'math':[90,89,99,78,97,93],'english':[89,94,80,94,94,90]}
#[1].直接写入参数test_dict
test_dict_df = pd.DataFrame(test_dict)
#[2].字典型赋值
test_dict_df = pd.DataFrame(data=test_dict)

那么,咱们就获得了一个DataFrame,以下:github

应该就是这个样子了。
方法二:使用from_dict方法:数据结构

test_dict_df = pd.DataFrame.from_dict(test_dict)

结果是同样的,再也不重复贴图。
其余方法:若是你的dict变量很小,例如{'id':1,'name':'Alice'},你想直接写到括号里:app

test_dict_df = pd.DataFrame({'id':1,'name':'Alice'}) # wrong style

这样是不行的,会报错ValueError: If using all scalar values, you must pass an index,是由于若是你提供的是一个标量,必须还得提供一个索引Index,因此你能够这么写:函数

test_dict_df = pd.DataFrame({'id':1,'name':'Alice'},pd.Index(range(1)))

后面的能够写多个pd.Index(range(3),就会生成三行同样的,是由于前面的dict型变量只有一组值,若是有多个,后面的Index必须跟前面的数据组数一致,不然会报错:spa

pd.DataFrame({'id':[1,2],'name':['Alice','Bob']},pd.Index(range(2)))  #must be 2 in range function.

关于选择列,有些时候咱们只须要选择dict中部分的键当作DataFrame的列,那么咱们可使用columns参数,例如咱们只选择'id','name'列:scala

test_dict_df = pd.DataFrame(data=test_dict,columns=['id','name']) #only choose 'id' and 'name' columns

这里就不在多写了,后续变动颜色添加内容。code

2. csv文件构建DataFrame(csv to DataFrame)

咱们实验的时候数据通常比较大,而csv文件是文本格式的数据,占用更少的存储,因此通常数据来源是csv文件,从csv文件中如何构建DataFrame呢? txt文件通常也能用这种方法。
方法一:最经常使用的应该就是pd.read_csv('filename.csv')了,用 sep指定数据的分割方式,默认的是','

df = pd.read_csv('./xxx.csv')

若是csv中没有表头,就要加入head参数

3. 在已有的DataFrame中,增长N列或者N行

加入咱们已经有了一个DataFrame,以下图:

3.1 添加列
此时咱们又有一门新的课physics,咱们须要为每一个人添加这门课的分数,按照Index的顺序,咱们可使用insert方法,以下:

new_columns = [92,94,89,77,87,91]
test_dict_df.insert(2,'pyhsics',new_columns)
#test_dict_df.insert(2,'pyhsics',new_columns,allow_duplicates=True)

此时,就获得了添加好的DataFrame,须要注意的是DataFrame默认不容许添加剧复的列,可是在insert函数中有参数allow_duplicates=True,设置为True后,就能够添加剧复的列了,列名也是重复的:

3.2 添加行
此时咱们又来了一位新的同窗Iric,须要在DataFrame中添加这个同窗的信息,咱们可使用loc方法:

new_line = [7,'Iric',99]
test_dict_df.loc[6]= new_line

可是十分注意的是,这样实际是的操做,若是loc[index]中的index已经存在,则新的值会覆盖以前的值。

固然也能够把这些新的数据构建为一个新的DataFrame,而后两个DataFrame拼起来。能够用append方法,不过不太会用,提供一种方法:

test_dict_df.append(pd.DataFrame([new_line],columns=['id','name','physics']))

本想一口气把CURD全写完,没想到写到这里就好累。。。其余后续新开篇章在写吧。
相关代码:(https://github.com/dataSnail/blogCode/blob/master/python_curd/python_curd_create.ipynb)(在DataFrame中删除N列或者N行)(在DataFrame中查询某N列或者某N行)(在DataFrame中修改数据)

相关文章
相关标签/搜索