day6--pandas

pandas–数据分析处理库
pandas是基于numpy构建的,为时间序列分析提供了很好的支持。pandas中有两个主要的数据结构,一个是Series,另一个是DataFrame。

  1. 导入pandas库,打开csv文件
    import pandas
    food_info = pandas.read_csv(“food_info.csv”)
    print(type(food_info)) —<class ‘pandas.core.frame.DataFrame’> #查看文件的格式
    #print(food_info.dtypes) #查看每一列数据的格式

  2. 使用函数head( m )来读取前m条数据,如果没有参数m,默认读取前五条数据;由于DataFrame包含了很多的行和列,Pandas使用省略号(…)来代替显示全部的行和列,可以使用colums属性来显示全部的列名;与Numpy一样,用shape属性来显示数据的格式。
    tail(n)-----读取数据后n行
    shape-----显示当前有多少样本,以及样本有多少个指标(列)
    first_rows = food_info.head()
    print(first_rows)
    print(food_info.head(3))
    print(food_info.columns)
    print(food_info.shape)

  3. Pandas使用loc[]方法来选择行的数据(当超出索引值,将报错)
    print(food_info.loc[0]) #取第一个数据
    print(food_info.loc[6]) #取第七个数据
    print(food_info.loc[8620]) #报错

  4. #object - For string values object----在pandas中就是string类型
    #int - For integer values
    #float - For float values
    #datetime - For time values
    #bool - For Boolean values
    print(food_info.dtypes) #输出所有列的字符类型

  5. 返回一个DataFrame,其中包含索引3、4、5和6处的行。
    print(food_info.loc[3:6]) #取第3,4,5,6行数据

    返回一个DataFrame,其中包含索引2、5和10处的行(两个方法可以实现)
    方法一:two_five_ten = [2,5,10]
    print(food_info.loc[two_five_ten])
    方法二:two_five_ten = [2,5,10]
    print(food_info.loc[[2,5,10]])

  6. 表示“NDB_No”列的Series对象
    ndb_col = food_info[“NDB_No”]
    print(ndb_col)
    或者,可以通过传入字符串变量来访问列。
    col_name = “NDB_No”
    ndb_col = food_info[col_name]
    print(ndb_col)

  7. 取指定两列的值
    columns = [“Zinc_(mg)”, “Copper_(mg)”]
    zinc_copper = food_info[columns]
    print(zinc_copper)

或者这样也可以实现
zinc_copper = food_info[[“Zinc_(mg)”, “Copper_(mg)”]]
print(zinc_copper)

  1. 可以使用tolist()函数转化为list
    print(food_info.columns) #输出所有列
    print(food_info.head(2)) #输出前两行

    col_names = food_info.columns.tolist() #输出所有列
    print(col_names)

  2. 输出所有以g结尾的列的前三行
    gram_columns = []

for c in col_names:
if c.endswith("(g)"):
gram_columns.append©
gram_df = food_info[gram_columns]
print(gram_df.head(3))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值