pandas的学习

import numpy as np
import pandas as pd

# 用pandas创建数据表
df = pd.DataFrame({"id": [1001, 1002, 1003, 1004, 1005, 1006],
                   "date": pd.date_range('20130102', periods=6),
                   "city": ['Beijing ', 'SH', ' guangzhou ', 'Shenzhen', 'shanghai', 'BEIJING '],
                   "age": [23, 44, 54, 32, 34, 32],
                   "category": ['100-A', '100-B', '110-A', '110-C', '210-A', '130-F'],
                   "price": [1200, np.nan, 2133, 5433, np.nan, 4432]},
                  columns=['id', 'date', 'city', 'category', 'age', 'price'])
print(df)

# 数据表信息查看
print('维度查看')
print(df.shape)

print('数据表基本信息')
print(df.info())

print('每列数据的格式')
print(df.dtypes)

print('某一列格式')
print(df['age'].dtype)

print('空值')
print(df.isnull())

print('查看某一列空值')
print(df['age'].isnull())

print('查看某一列的唯一值')
print(df['age'].unique())

print('查看数据表的值')
print(df.values)

print('查看列名称')
print(df.columns)

print('查看前3行数据,后3行数据')
print(df.head(3))
print(df.tail(3))

# 数据表清洗
print('用数字0填充空值')
print(df.fillna(value=0))

print('使用price的均值对NaN进行填充')
print(df['price'].fillna(df['price'].mean()))

print('清除city字段的字符空格')
df['city'] = df['city'].map(str.strip)
print('大小写转换')
df['city'] = df['city'].str.lower()
print(df)

print('更改数据格式')
print(df['age'].astype('float'))

print('更改列名称')
print(df.rename(columns={'category': 'category-size'}))

print('删除后出现的重复值')
print(df['city'].drop_duplicates())

print('删除先出现的重复值')
print(df['city'].drop_duplicates(keep='last'))

print('数据替换')
print(df['city'].replace('sh', 'shanghai'))

# 数据预处理
df1 = pd.DataFrame({"id": [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008],
                    "gender": ['male', 'female', 'male', 'female', 'male', 'female', 'male', 'female'],
                    "pay": ['Y', 'N', 'Y', 'Y', 'N', 'Y', 'N', 'Y', ],
                    "m-point": [10, 12, 20, 40, 40, 40, 30, 20]})
print(df1)
print('数据表合并')
df_inner = pd.merge(df, df1, how='inner')  # 匹配合并,交集
print(df_inner)
df_left = pd.merge(df, df1, how='left')  #
print(df_left)
df_right = pd.merge(df, df1, how='right')
print(df_left)
df_outer = pd.merge(df, df1, how='outer')  # 并集
print(df_outer)

print('设置索引列')
df_inner.set_index('id')

print('按照特定列的值排序')
print(df_inner.sort_values(by=['age']))

print('按照索引列排序')
print(df_inner.sort_index())

print('如果price列的值>3000,group列显示high,否则显示low')
df_inner['group'] = np.where(df_inner['price'] > 3000, 'high', 'low')
print(df_inner)

print('对复合多个条件的数据进行分组标记')
df_inner.loc[(df_inner['city'] == 'beijing') & (df_inner['price'] >= 4000), 'sign'] = 1
print(df_inner)

print('对category字段的值依次进行分列,并创建数据表,索引值为df_inner的索引列,列名称为category和size')
split = pd.DataFrame((x.split('-') for x in df_inner['category']), index=df_inner.index, columns=['category', 'size'])
print(split)

print('将完成分裂后的数据表和原df_inner数据表进行匹配')
df_inner = pd.merge(df_inner, split, right_index=True, left_index=True)
print(df_inner)

# 数据提取
# 主要用到的三个函数:loc,iloc和ix,loc函数按标签值进行提取,iloc按位置进行提取,ix可以同时按标签和位置进行提取。
print('按索引提取单行的数值')
print(df_inner.loc[3])

print('按索引提取区域行数值')
print(df_inner.iloc[0:5])

print('重设索引')
print(df_inner.reset_index())

print('设置日期为索引')
df_inner = df_inner.set_index('date')
print(df_inner)

print('提取4日之前的所有数据')
print(df_inner[:'2013-01-04'])

print('使用iloc按位置区域提取数据')
print(df_inner.iloc[:3, :2])  # 冒号前后的数字不再是索引的标签名称,而是数据所在的位置,从0开始,前三行,前两列。

print('使用iloc按位置单独提取数据')
print(df_inner.iloc[[0, 2, 5], [4, 5]])  # 提取第0、2、5行,4、5列

print('使用ix按索引标签和位置混合提取数据')
print(df_inner.ix[:'2013-01-03', :4])  # 2013-01-03号之前,前四列数据

print('判断city列的值是否为北京')
print(df_inner['city'].isin(['beijing']))

print('判断city列里是否包含beijing和shanghai,然后将符合条件的数据提取出来')
print(df_inner.loc[df_inner['city'].isin(['beijing', 'shanghai'])])

print('提取前三个字符,并生成数据表')
category = df['category']
print(pd.DataFrame(category.str[:3]))

# 数据筛选
print('使用“与”进行筛选')
print(df_inner.loc[
          (df_inner['age'] > 25) & (df_inner['city'] == 'beijing'), ['id', 'city', 'age', 'category_x', 'gender']])

print('使用“或”进行筛选')
print(df_inner.loc[
          (df_inner['age'] > 25) | (df_inner['city'] == 'beijing'), ['id', 'city', 'age', 'category_x',
                                                                     'gender']].sort_values(['age']))

print('使用“非”条件进行筛选')
print(df_inner.loc[(df_inner['city'] != 'beijing'), ['id', 'city', 'age', 'gender']].sort_values(['id']))

print('对筛选后的数据按city列进行计数')
print(df_inner.loc[(df_inner['city'] != 'beijing'), ['id', 'city', 'age', 'gender']].sort_values(
    ['id']).city.count())

print('使用query函数进行筛选')
print(df_inner.query('city == ["beijing", "shanghai"]'))

print('对筛选后的结果按price进行求和')
print(df_inner.query('city == ["beijing", "shanghai"]').price.sum())

# 数据汇总
print('对所有的列进行计数汇总')
print(df_inner.groupby('city').count())

print('按城市对id字段进行计数')
print(df_inner.groupby('city')['id'].count())

print('对两个字段进行汇总计数')
print(df_inner.groupby(['city', 'size'])['id'].count())

print('对city字段进行汇总,并分别计算price的合计和均值')
print(df_inner.groupby('city')['price'].agg([len, np.sum, np.mean]))

# 数据统计
print('简单的数据采样')
print(df_inner.sample(n=3))

print('手动设置采样权重')
weights = [0, 0, 0, 0, 0.5, 0.5]
print(df_inner.sample(n=2, weights=weights))

print('采样后不放回')
print(df_inner.sample(n=6, replace=False))

print('采样后放回')
print(df_inner.sample(n=6, replace=True))

print('数据表描述性统计')
print(df_inner.describe().round(2).T)  # round函数设置显示小数位,T表示转置

print('计算列的标准差')
print(df_inner['price'].std())

print('计算两个字段间的协方差')
print(df_inner['price'].cov(df_inner['m-point']))

print('数据表中所有字段间的协方差')
print(df_inner.cov())

print('两个字段的相关性分析')
print(df_inner['price'].corr(df_inner['m-point']))  # 相关系数在-1到1之间,接近1为正相关,接近-1为负相关,0为不相关

print('数据表的相关性分析')
print(df_inner.corr())

# 数据输出
print('写入Excel')
df_inner.to_excel('excel_to_python.xlsx', sheet_name='bluewhale_cc')

print('写入到CSV')
df_inner.to_csv('excel_to_python.csv')

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值