基于pandas数据样本行列选取的方法

yipeiwu_com6年前Python基础

注:以下代码是基于python3.5.0编写的

import pandas
food_info = pandas.read_csv("food_info.csv")
# ------------------选取数据样本的第一行--------------------
print(food_info.loc[0])
#------------------选取数据样本的3到6行----------------------
print(food_info.loc[3:6])
#------------------head选取数据样本的前几行------------------
print(food_info.head(2))
# ------------------选取数据样本的2,5,10行,两种方法-----------
# print(food_info.loc[[2,5,10]])     #方法一 
two_five_ten = [2,5,10]         #方法二
print(food_info.loc[two_five_ten])
# ------------------选取数据样本的NDB_No列--------------------
# ndb_col = food_info["NDB_No"]     #方法一 
col_name = "NDB_No"           #方法二
ndb_col = food_info[col_name]
print(ndb_col)
# ------------------选取数据样本的多列-------------------
# zinc_copper = food_info[["Zinc_(mg)", "Copper_(mg)"]]
columns = ["Zinc_(mg)", "Copper_(mg)"]
zinc_copper = food_info[columns]
print(zinc_copper)
# ---------------------综合小例子----------------------------
col_names = food_info.columns.tolist()   #把所有的行转化成list
print(col_names)
gram_columns = []
for c in col_names:            #遍历col_names,找出所有以(g)结尾的位置
  if c.endswith("(g)"):
    gram_columns.append(c)
print(gram_columns)
gram_df = food_info[gram_columns]     #把所有以(g)结尾的列存放到gram_df
print(gram_df.head(3)) 

以上这篇基于pandas数据样本行列选取的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详解Python中contextlib上下文管理模块的用法

咱们用的os模块,读取文件的时候,其实他是含有__enter__ __exit__ 。  一个是with触发的时候,一个是退出的时候。 with file('nima,'r...

python分割和拼接字符串

关于string的split 和 join 方法对导入os模块进行os.path.splie()/os.path.join() 貌似是处理机制不一样,但是功能上一样。1.string.s...

djano一对一、多对多、分页实例代码

昨日内容: ORM高级查询 -filter id=3 id__gt=3 id__lt=3 id__lte=3 id__gte=3 -in /not in .filter(id__i...

用python实现批量重命名文件的代码

下面是最终代码 (windows下实现的) 复制代码 代码如下: # -*- coding: cp936 -*- import os path = 'D:\\图片\\' for file...

解决sublime+python3无法输出中文的问题

Tools -> Build System -> Build New System { "cmd": ["/usr/local/bin/python3", "-u",...