pandas模块


参考资料:


PandasPython核心数据分析支持库,是 Python 中统计计算生态系统的重要组成部分。

import pandas as pd
import numpy as np

data = pd.read_csv("train.csv")

#see the first 10 rows
data.head(10)

#check the rows and cols
data.shape
data.info()

#print the name of all the columns
data.columns
#
len

#index
data.index

#检查空值
pd.isnull(object)

# 查看数据统计信息
data.describe()

# 查看某一列唯一实体
data["col_name"].unique()

# 删除特征
df.drop('feature_variable_name', axis=1)
#axis 0 表示行,1 表示列

# 通过特征名取数据
df.loc[feature_name]

# 对 DataFrame 使用函数
df["height"] = df["height"].apply(lambda x: 2 * x)

# 重命名行
df.rename(columns = {df.columns[2]:'size'}, inplace=True)
# 设置索引为 1~10
df.set_index(pd.RangeIndex(1, 11), inplace = True)

# 更改列名
df.columns=['grammer', 'score', 'cycle']
#将所有列倒序排列
df_desc = df.iloc[:, ::-1]

基础

1. 创建

一维的Series和二维的 DataFrame

pd.Series([1,2,3],index=[0,1,2])

# 0    1
# 1    2
# 2    3
# dtype: int64

pd.DataFrame()

# Empty DataFrame
# Columns: []
# Index: []
dates=pd.date_range('20200511',periods=3)
dates

# DatetimeIndex(['2020-05-11', '2020-05-12', '2020-05-13'], dtype='datetime64[ns]', freq='D')
pd.DataFrame(np.random.randn(3,4),index=dates,columns=list('abcd'))
a b c d
2020-05-11 -1.712588 0.403376 -0.152608 -0.428465
2020-05-12 -1.259988 -0.310385 -0.816578 0.321397
2020-05-13 -0.444678 -1.894342 0.172485 0.717187

2. 查看

  • df.head(),k值默认为5.
  • df.tail(),k值默认为5
  • df.index
  • df.columns
  • df.describe(),查看数据的分布情况
  • df.info()

3. 选择

  • 获取单列,df.adf['a']等效
  • 获取行,用 [ ] 切片行
  • 按标签选择
  • 按位置选择

4. 操作

  • Series操作类似字典类型,含:保留字in操作、.get(key,default=None)方法
  • .reindex(),改变或重排SeriesDataFrame索引数据输入输出
  • .drop(),删除SeriesDataFrame指定行或列索引,默认0轴(竖的)
  • apply()
def age_fun(x):
    if x < 12: return "children"
    elif x < 18: return "teenager"
    elif x < 65: return "audlt"
    else: return "old"

train["Age"] = train["Age"].apply(age_fun)

5. 运算

  1. 算术运算根据行列索引,补齐后运算,运算默认产生浮点数。
  2. 补齐时缺项填充NaN(空值)
  3. 不同维度数据间运算为广播运算
  4. +b.add(a,fill_value=NaN)
  5. 比较运算

排序

  1. .sort_index(axis=0,ascending=True),根据索引排序,默认升序
  2. Series.sort_values(axis=0,ascending=True)
    DataFrame.sort_values(by,axis=0,ascending=True)

输入输出

CSV

  • df.to_csv('___.csv')
  • pd.read_csv('___.csv')

Excel

  • df.to_excel('___.xlsx', sheet_name='Sheet1')
  • pd.read_excel('___.xlsx', 'Sheet1', index_col=None, na_values=['NA'])

文章作者: ╯晓~
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 ╯晓~ !
评论
  目录