python pandas

import numpy as np
import pandas as pd

df = pd.DataFrame({'a': [1, 4, 2, 3, 3, 2, 3, 1],
                   'b': [4, 3, 2, 1, 1, 3, 4, 1],
                   'c': [2, 3, 1, 2, 4, 2, 4, 2]})
print(df)

# 1.基本信息
print(df.dtypes)
print(df.info())
print(df.describe())
print(df.index)
print(df.columns)

# 2.數據操作(增刪改查)
# 列增加刪除
df['d'] = [1, 3, 2, 4, 3, 3, 4, 1] # 增加d列
df['e'] = [4, 3, 4, 2, 1, 2, 3, 4] # 增加e列
print(df)
del df['d'] # 刪除列索引爲d的列
df.drop(['e'], axis=1, inplace=True) # 刪除列索引爲e的列
print(df)

# 行增加刪除
df_add = pd.DataFrame({'a': [4, 5], 'b': [7, 8], 'c': [10, 11]})
df = pd.concat([df, df_add], ignore_index=True) # 增加行
print(df)
df.drop([3, 4], inplace=True) # 刪除行索引爲3和4的行
print(df)

# 修改數據
df.ix[0][0] = 1 # 修改數據
df.ix[0][1] = 2 # 修改數據
df.ix[0][2] = 3 # 修改數據
print(df)
df.ix[0][0] = 1 # 修改數據
df.ix[0][1] = 4 # 修改數據
df.ix[0][2] = 2 # 修改數據
print(df)

# 查詢數據
print(df.a) # 查看a列
print(df['a']) # 查看a列
print(df[['a', 'b']]) # 查看a、b兩列
print(df[0:2]) # 查看前兩行
print(df.loc[0, :]) # 查看0行
print(df.iloc[0, :]) # 查看0行
print(df.loc[:, ['a', 'b']]) # 查看a、b兩列
print(df.iloc[:, [0, 1]]) # 查看a、b兩列

# 按條件選取數據
data = df[df['a'] > 1] # 選取a列中大於1的數據
print(data)
data = df[(df['a'] >= 2) & (df['a'] <= 3)] # 選取a列中大於1小於3的數據
print(data)

# 3.排序
print(df.sort_index()) # 按行索引進行排序
print(df.sort_index(axis=1)) # 按列索引進行排序
print(df.sort_values(by=['a'])) # 對a列值進行排序
print(df.sort_values(by=0, axis=1)) # 對0行值進行排序

# 4.合併
# 縱向合併
df_concat = pd.DataFrame({'a': [4, 5],
                          'b': [5, 6],
                          'c': [7, 8]})
df_concat = pd.concat([df, df_concat], ignore_index=True) # 縱向合併
print(df_concat)

# 橫向合併
df_concat = pd.DataFrame({'d': [0, 1, 2, 3, 4, 5, 6, 7]})
df_concat = pd.concat([df, df_concat], ignore_index=True, axis=1) # 橫向合併
print(df_concat)

# 5.連接
df_merge = pd.DataFrame({'a': [1, 2, 3, 4],
                         'd': [3, 4, 2, 2]})
df_merge = pd.merge(df, df_merge, on='a', how='left')
print(df_merge)

# 6.數據統計
print(df.mean())
print(df.median())
print(df.var())
print(df.max())
print(df.min())

# 7.缺失值處理
df = df.fillna(0)
print(df)

# 8.分組(比賽中經常用)
group = df.groupby('a').agg([np.mean, np.median, np.max, np.min])
print(group)

group = df.groupby(['a', 'c']).count() # 等價於group = df['b'].groupby([df['a'], df['c']]).count()
group = group.unstack()
print(group)

group = df['b'].groupby(df['a']).count()
print(group)

# 9.透視表
table = pd.pivot_table(df, values='c', index=['a'], columns=['b'], aggfunc=np.sum)
print(table)

# 10.crosstab+reset_index(比賽中經常用)
a_b_count = pd.crosstab(index=df.a, columns=df.b) # crosstab()可以對離散變量的不同取值進行統計
print(a_b_count)
a_b_ratio = a_b_count.div(a_b_count.sum(axis=1), axis=0)
print(a_b_ratio)
a_b = a_b_ratio.reset_index() # 重新設置df的index,範圍爲0~len(df),並且將原來的行索引作爲新的一列
print(a_b)
a_b = a_b_ratio.reset_index(drop=True) # 重新設置df的index,範圍爲0~len(df)
print(a_b)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章