python数据分析pandas基础用法

import pandas as pd

df = pd.read_csv('cancer_data.csv')
df.head()

# 返回 dataframe 维度的元组
df.shape

# 返回列的数据类型
df.dtypes

# 虽然供诊断的数据类型是对象,但进一步的
# 调查显示,它是字符串
type(df['diagnosis'][0])

# 返回每列数据的有效描述性统计
df.describe()

# 但是也可以指定你希望返回的行数
df.head(20)

# `.tail()` 返回最后几行,但是也可以指定你希望返回的行数
df.tail(2)

# 查看每列的索引号和标签
for i, v in enumerate(df.columns):
    print(i, v)

# 选择从 'id' 到最后一个均值列的所有列
df_means = df.loc[:,'id':'fractal_dimension_mean']
df_means.head()

# 用索引号重复以上步骤
df_means = df.iloc[:,:12]
df_means.head()

保存均值 dataframe ,以便稍后使用。

df_means.to_csv('cancer_data_edited.csv', index=False)

 

 

# 用均值填充缺失值
mean=cancer['smoothness_mean'].mean()

保存两种方法
cancer['smoothness_mean']=cancer['smoothness_mean'].fillna(mean)

cancer['smoothness_mean'].fillna(mean,inplace=True)

# 丢弃重复
cancer.drop_duplicates(inplace=True)

# 再次检查数据中的重复,确认修改
cancer.duplicated()

sum(cancer.duplicated())

重命名列

由于之前修改了数据集,使其仅包括肿瘤特征的均值,因此每个特征末尾好像不需要 "_mean" 。而且,稍后输入分析还要多耗费时间。我们现在想一些要分配给列的新标签。

new_labels = []
for col in df.columns:
    if '_mean' in col:
        new_labels.append(col[:-5])  # 不包括最后 6 个字符
    else:
        new_labels.append(col)

# 列的新标签
new_labels

# 为数据框中的列分配新标签
df.columns = new_labels

# 显示数据框的前几行,确认更改
df.head()

# 将其保存,供稍后使用
df.to_csv('cancer_data_edited.csv', index=False)

类型转换

df['timestamp']=pd.to_datetime(df['timestamp'])

但是保存后数据类型不会生效,打开后需要重新转换

 

 

使用pandas绘图

import pandas as pd
% matplotlib inline
df=pd.read_csv('powerplant_data_edited.csv')
df.info()
df.hist()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9568 entries, 0 to 9567
Data columns (total 5 columns):
AT    9568 non-null float64
V     9568 non-null float64
AP    9568 non-null float64
RH    9568 non-null float64
PE    9568 non-null float64
dtypes: float64(5)
memory usage: 373.8 KB

 

df.hist(figsize=(8,8));  扩大字体并显示不必要的内容(;的作用)

df['AP'].hist(figsize=(8,8));

单独显示

df['AP'].plot(kind='hist');

df['AP'].value_counts()

绘制饼状图

df['AP'].value_counts().plot(kind='pie',figsize=(8,8));

pd.plotting.scatter_matrix(df,figsize=(15,15))

散点图

 

 

制定xy的散点图

 

df.plot(x='A',y='B',kind='scatter');

# 绘制每个变量的箱线图
df['AP'].plot(kind='box');

 

 

df['AT'].value_counts().plot(kind='bar');

 

 

 

import pandas as pd
%matplotlib inline
df=pd.read_csv('store_data.csv')

df.head()

 weekstoreAstoreBstoreCstoreDstoreE
02014-05-0426438257389362311294
12014-05-1164445736563470922907
22014-05-1896462552425354474736
32014-05-2559601074082646063949
42014-06-0174127374320839853023

 

mask = df['week'] <='2016-04-03'
print(mask)

28      True
29      True
       ...  
170    False
171    False
172    False
173    False

或者

df_week=df[ df['week'] <='2016-04-03' ]

或者  df_week=df[mask]

df_week

df_week.head()

 

df_week.describe()

 storeAstoreBstoreCstoreDstoreE
count1.01.01.01.01.0
mean2054.01390.05112.05513.02536.0
stdNaNNaNNaNNaNNaN
min2054.01390.05112.05513.02536.0
25%2054.01390.05112.05513.02536.0
50%2054.01390.05112.05513.02536.0
75%2054.01390.05112.05513.02536.0
max2054.01390.05112.05513.02536.0

 

df.tail(20)

 weekstoreAstoreBstoreCstoreDstoreE
1802017-10-15855611984479259952508
1812017-10-22375169739904236360
1822017-10-2949979759429045682393
1832017-11-0512785180061635157578
1842017-11-1213712261545576952599
1852017-11-199960852945017631505
1862017-11-2668665011540147363232
1872017-12-035179385061216778113
1882017-12-109348562454465448227
1892017-12-1753108647568070493578
1902017-12-2489769503624038822890
1912017-12-31118751527671152651701
1922018-01-07897811312415850193842
1932018-01-1469634014421571533097
1942018-01-2155533971376162553071
1952018-01-282826351775955581028
1962018-02-0448536503418759561458
1972018-02-119202367745406186243
1982018-02-1835127511415155963501
1992018-02-2575606904356950452585

 

# 最后一个月的总销售额
df.iloc[196:, 1:].sum()

storeA    25127
storeB    24595
storeC    16447
storeD    22783
storeE     7787
dtype: int64

# 平均销售额
df.mean()

storeA    5865.480
storeB    6756.710
storeC    4942.105
storeD    5431.405
storeE    2580.025
dtype: float64

# 2016 年 3 月 13 日的销售额
df[df['week'] == '2016-03-13']

 weekstoreAstoreBstoreCstoreDstoreE
972016-03-1320541390511255132536

 

# C 店销售额最低的一周
df[df['storeC'] == df['storeC'].min()]

 weekstoreAstoreBstoreCstoreDstoreE
92014-07-06856732289273277168


# 最近 3 个月的总销售额
last_three_months = df[df['week'] >= '2017-12-01']
last_three_months.iloc[:, 1:].sum()

storeA    87591
storeB    79394
storeC    66538
storeD    75190
storeE    27334
dtype: int64

 

 

# 上个月的销售额
df.iloc[196:, 1:].sum().plot(kind='bar');

# 平均销售额
df.mean().plot(kind='pie');

# 2016 年 3 月 13 日所在的那一周的销售额
sales = df[df['week'] == '2016-03-13']
sales.iloc[0, 1:].plot(kind='bar');

 

# 过去 3 个月的销售额
last_three_months = df[df['week'] >= '2017-12-01']
last_three_months.iloc[:, 1:].sum().plot(kind='pie');

 

让标签顺序一致,不按照返回值排序,在value_count()后面加入index

df_a=df[ df['income'] == '<=50K' ]

ind=df_a['education'].value_counts().index

df_a['education'].value_counts()[idx].plot(kind='bar');

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值