Python pandas数据样本行列选取实战指南

木白
木白
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍基于Python 3.5.0及pandas库的数据样本行列选取方法。通过loc索引、head函数及列名列表,演示如何精准提取特定行与列数据,并结合实际CSV文件处理示例,帮助开发者掌握高效的数据筛选技巧。

注:以下代码是基于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 相关产品和应用

全部下载

专题列表