CSDN机器学习笔记六 Pandas简单操作

本文介绍 Pandas 库的基本操作及应用案例,包括数据读取、处理和分析等关键步骤,帮助读者掌握使用 Pandas 进行数据分析的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pandas


一、简介

是基于Numpy的一种工具,为了解决数据分析任务而创建的,引入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。pandas提供了大量能使我们快速便捷地处理数据的函数和方法。
官网 《10分钟入门》

二、基本操作

1.导入库

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

2.创建对象

可以通过传递一个list对象来创建一个Series。

import pandas as pd

s = pd.Series([1,3,5,np.nan,6,8])
print (s)

输出:
0 1.0
1 3.0
2 5.0
3 NaN
4 6.0
5 8.0
dtype: float64

自己构造一个series

series_custom = Series(rt_scores , index=film_names)

一般对dataFrame进行操作,dataFrame是由series组成,series底层是一个ndarray结构。

3.传递一个numpy array,时间索引创建DataFrame

import pandas as pd

dates = pd.date_range('20130101', periods=6)
print (dates)

输出:
DatetimeIndex([‘2013-01-01’, ‘2013-01-02’, ‘2013-01-03’, ‘2013-01-04’,
‘2013-01-05’, ‘2013-01-06’],
dtype=’datetime64[ns]’, freq=’D’)

4.传递一个字典对象创建DataFrame

import pandas as pd

df2 = pd.DataFrame({ 'A' : 1.,
 'B' : pd.Timestamp('20130102'),
 'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
 'D' : np.array([3] * 4,dtype='int32'),
 'E' : pd.Categorical(["test","train","test","train"]),
 'F' : 'foo' })
print (df2)

输出:
A B C D E F
0 1.0 2013-01-02 1.0 3 test foo
1 1.0 2013-01-02 1.0 3 train foo
2 1.0 2013-01-02 1.0 3 test foo
3 1.0 2013-01-02 1.0 3 train foo

5.查看不同列的数据类型

import pandas as pd

df2 = pd.DataFrame({ 'A' : 1.,
 'B' : pd.Timestamp('20130102'),
 'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
 'D' : np.array([3] * 4,dtype='int32'),
 'E' : pd.Categorical(["test","train","test","train"]),
 'F' : 'foo' })
print (df2.dtypes)

输出:
dtype: object

5.数据读取,加载csv

import pandas 
food_info = pandas.read_csv("food_info.csv")
print (type(food_info))
print (food_info.dtpe)
print (help(pandas.read_csv))  返回函数的说明

这里写图片描述

展示前三行

food_info.head(3) 

这里写图片描述
默认第一行作为表头。

展示最后几行

food_info.tail(4) 

列名

food_info.columns 

shape

food_info.shape

返回一共多少行。

取一列

ndb_col = food_info['NDB_No"]
print (ndbcol)

取多个列

columns = ["col1","col2]
zinc_copper = food_info[columns]

找某些列

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

运行结果:
这里写图片描述

新加一个列

food_info["Iron_(g)"] = iron_grams
print (food_info.shape)

求最大值
max()

排序

food_info.sort_values("Sodium_(mg)", inplace=True)

print (food_info)
food_info.sort_values("Sodium_(mg)",inplace= True,ascending=False)
print (food_info["Sodium_(mg)"])

运行结果:
这里写图片描述

示例

import pandas as pd
import numpy as np
titanicsurvival = pd.read_csv("titanic_train.csv")
titanic_suvival.head()

age = titanic_surival["Age"] #年龄拿出来
print (age.loc[0:10])
# 没有没缺失值
age_is_numm = pd.isnull(age)

这里写图片描述

age_is_null = pd.isnull(age)
这里写图片描述

age_null_true = age[age_is_null]
age_null_count = len(age_null_true)
print (age_null_count)

输出有多少缺失值

mean_age = sum(titanic_survival["Age"]) / len(titanic_survival["Age"])
print (mean_age)
返回 nan

筛选

good_ages = titanic_survival["Age"].mean()
print (corrent_mean_age)

统计各仓位价格

passenger_classes = [1,2,3]
fares_by_class = {}
for this_class in passenger_classes:
  pclass_rows = titanic_survival[titanic_survival["Pclass"] == this_class]
  pclass_fares = pclass_rows["Fare"]
  fare_for_class=pclass_fares.mean()
  fares_by_class[this_class] = fare_for_class
print fares_by_class

筛选列
这里写图片描述

指定按哪个列排序
这里写图片描述

titanic_reindexed = new_titanic_survival.reset_index(drop=True)

把乱序重新指定排序。

自定义函数

# This function returns the nundredth item from the pool
def hundredth_row(column):
    # Extract the hundredth item
   hundredth_item = column.loc[99]
   return hundredth_item

# Return the hundredth item from each column
hundredth_row = titanic_survival.apply(hundredth_row)
print (hundredth_row)

这里写图片描述

这里写图片描述

另一个例子:
把1,2,3转为对应字符串:

def which_class(row):
    pclass = row['Pclass']
    if pd.isnull(pclass):
        return "Unknown"
    elif pclass ==1:
        return "First Class"
    elif pclass ==2:
        return Second Class"
    elif pclass ==3:
        return "Third Class"

classes = titanic_survival.apply(which_class,axis=1)
print (classes)

计算获救比例的示例:
这里写图片描述

匿名函数

下节课:
怎么建立模型、建立标准、预处理方法 ,基于样本不均衡数据。

### 黑马程序员机器学习笔记与资源 黑马程序员作为一家知名的IT培训机构,在其课程体系中涵盖了广泛的编程技术领域,其中包括机器学习相关内容。以下是有关于黑马程序员机器学习的一些常见知识点以及可能获取到的学习资料的方式。 #### 一、机器学习基础概念 机器学习是一种通过数据训练模型来完成特定任务的技术方法[^1]。它主要分为监督学习、无监督学习和强化学习三大类。其中,监督学习涉及分类和回归问题;无监督学习则用于聚类分析和降维处理;而强化学习则是让算法在一个环境中自主探索并采取行动以最大化某种累积奖励。 #### 二、黑马程序员机器学习课程特点 黑马程序员提供的机器学习课程通常会覆盖Python语言的基础应用、NumPy/Pandas数据分析库的操作技巧、Scikit-Learn框架下的经典算法实现等内容[^2]。此外还会深入讲解深度学习理论及其实践案例研究,比如TensorFlow或者PyTorch工具包的应用场景探讨等。 #### 三、如何获得相关笔记或资料? 对于希望得到黑马程序员内部使用的教材文档的同学来说,有几种途径可以尝试: - **官方渠道购买正版书籍**:可以通过出版社官网或者其他正规电商平台购入由该机构编写的正式出版物。 - **参加线下/线上培训项目**:报名成为学员之后自然能够接触到完整的讲义文件以及其他配套练习素材。 - **网络社区分享查找二手资源**:部分前学员可能会将自己的课堂记录上传至CSDN博客、GitHub仓库等地供他人参考学习(注意版权归属情况)。 ```python import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression # 创建虚拟数据集 X, y = make_classification(n_samples=1000, n_features=20, n_informative=2, n_redundant=10, random_state=42) # 划分训练集合测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # 初始化逻辑回归模型 clf = LogisticRegression() # 训练模型 clf.fit(X_train, y_train) # 输出得分 print(f'Test Accuracy: {clf.score(X_test, y_test)}') ``` 上述代码片段展示了利用sklearn中的Logistic Regression进行简单分类预测的一个例子[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI星球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值