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

yipeiwu_com7年前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的gevent框架下执行异步的Solr查询的教程

 我经常需要用Python与solr进行异步请求工作。这里有段代码阻塞在Solr http请求上, 直到第一个完成才会执行第二个请求,代码如下:   impor...

Python 实现简单的shell sed替换功能(实例讲解)

code: f = open('yesterday','r',encoding='utf-8') f2 = open('yesterday.bak','w',encoding='ut...

django表单实现下拉框的示例讲解

方法一: queue = forms.ModelChoiceField(label=u'队列',queryset=Queue.objects.all()) 方法二: clas...

python Matplotlib底图中鼠标滑过显示隐藏内容的实例代码

python Matplotlib底图中鼠标滑过显示隐藏内容的实例代码

在使用Matplotlib画图过程中,有些内容必须鼠标点击或者划过才可以显示,这个问题可以依赖于annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,....

Python yield使用方法示例

1. iterator叠代器最简单例子应该是数组下标了,且看下面的c++代码: 复制代码 代码如下:int array[10];for ( int i = 0; i < 10; i...