pandas速记

import numpy as np
import pandas as pd
# ---------------------pandas Series & DataFrame-------------#
s = pd.Series([1, 3, 6, np.nan, 44, 1])
print(s)  # 左边有索引
# 0     1.0
# 1     3.0
# 2     6.0
# 3     NaN
# 4    44.0
# 5     1.0
dates = pd.date_range('20180104',periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates,
                  columns=['prices', 'name', 'class', 'dataframe'])  # 指定dates是索引,指定列名
print(df)
print(df['prices'])  # 访问prices列的元素
# 另外一种生成DataFrame的方式
df = pd.DataFrame({
    'prices': pd.Timestamp('20180725'),
    'name': pd.Series(1, index=list(range(4)), dtype='float32'),
    'data': pd.Categorical(["test", "train", "test", "train"])
})
print(df)
print(df.dtypes)  # 每列的数据类型
print(df.index)  # 行索引
print(df.columns)  # 列索引
print(df.values)  # 数据
print(df.describe())  # 描述,均值方差

# --------------------pandas选择数据------------------------#
dates = pd.date_range('20180104',periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates,
                  columns=['prices', 'name', 'class', 'dataframe'])  # 指定dates是索引,指定列名
print(df)
print(df.prices)  # 两种访问某一列的方式
print(df['prices'])
print(df[0:2])  # 前两行元素
print(df['20180104':'20180106'])  # 前三行元素
"""
loc:用用户设定的行列索引名访问
iloc:用数字索引访问
ix:混合两种访问方式
"""
print(df.loc['20180104'])
print(df.loc[:, ['prices', 'class']])  # prices列和class列的所有行元素
print(df.loc['20180104', :])  # 04行所有元素
print(df.loc['20180104': '20180106', ['prices', 'class']])  # 从04到06的prices列和class列元素
print("----------------------")
print(df)
print(df.iloc[1, 1])
print(df.iloc[3:5, 1:3])
print(df.iloc[[1, 3, 5], 1:3])

print(df.ix[:3, ['prices', 'class']])
print(df[df.prices > 0])  # 判断prices列元素大于0的所有列
print("========================================")
# -------------------------------pandas 设置数据----------------#
dates = pd.date_range('20180104',periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates,
                  columns=['prices', 'name', 'class', 'dataframe'])  # 指定dates是索引,指定列名
print(df)
df.iloc[0, 0] = 9999
df.loc['20180104', 'class'] = 5555
df.name[df.prices < 0] = 19999  # prices列元素小于0的行对应的name列的值赋值19999
print(df)
df['color'] = pd.Series(['red', 'green', 'gray', 'black', 'white', 'orange'],
                        index=dates)  # 添加元素,添加只能用['color']方法
print(df)
# -------------------------pandas 处理丢失数据-------------------------------#
df.iloc[0, 1] = np.nan
df.iloc[1, 3] = np.nan
print(df)
df.dropna(axis=0, how='any')  # 0:对行操作,1对列操作,‘any’只要存在就删掉,‘all’全是nan才删掉
print(df)  # 还是原来的df
print(df.dropna(axis=0, how='any'))  # 新得到的df
print(df.fillna(value=0))
print(df)  # fillna仍然不改变df
print(df.isnull())  # 返回true false的df
print(np.any(df.isnull()) == True)  # true  有nan
print(np.all(df.isnull()) == True)  # false 不全是nan
print(df)  # 仍然不改变

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 读写文件
data = pd.read_csv('students.csv')
print(data)
data.to_pickle('student.pickle')
# 定义资料集
df1 = pd.DataFrame(np.ones((3, 4))*0, columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.ones((3, 4))*1, columns=['a', 'b', 'c', 'd'])
df3 = pd.DataFrame(np.ones((3, 4))*2, columns=['a', 'b', 'c', 'd'])

# concat纵向合并
res = pd.concat([df1, df2, df3], axis=0)

# 打印结果,但是index并没有更新
print(res)

# 重置index
res = pd.concat([df1, df2, df3], axis=0, ignore_index=True)
print(res)

# 定义资料集
df1 = pd.DataFrame(np.ones((3, 4))*0, columns=['a', 'b', 'c', 'd'], index=[1, 2, 3])
df2 = pd.DataFrame(np.ones((3, 4))*1, columns=['b', 'c', 'd', 'e'], index=[2, 3, 4])

# 纵向"外"合并df1与df2
res = pd.concat([df1, df2], axis=0, join='outer')

print(res)  # 没有元素对应的地方为nan

# 纵向"内"合并df1与df2
res = pd.concat([df1, df2], axis=0, join='inner')  # 只合并两个都有的列

# 打印结果
print(res)


# 依照`df1.index`进行横向合并
res = pd.concat([df1, df2], axis=1, join_axes=[df1.index])

# 打印结果
print(res)
#     a    b    c    d    b    c    d    e
# 1  0.0  0.0  0.0  0.0  NaN  NaN  NaN  NaN
# 2  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
# 3  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0

# 移除join_axes,并打印结果
res = pd.concat([df1, df2], axis=1)
print(res)

df1 = pd.DataFrame(np.ones((3, 4))*0, columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.ones((3, 4))*1, columns=['a', 'b', 'c', 'd'])
df3 = pd.DataFrame(np.ones((3, 4))*2, columns=['a', 'b', 'c', 'd'])

print(df1.append(df2, ignore_index=True))
print(df2.append([df1, df3], ignore_index=True))
s1 = pd.Series([1,2,3,4], index=['a','b','c','d'])
print(df1.append(s1, ignore_index=True))

# -----------------------------pandas plot-----------------------#

# 随机生成1000个数据
data = pd.Series(np.random.randn(1000), index=np.arange(100, 1100))
# 为了方便观看效果, 我们累加这个数据
data = data.cumsum()
# pandas 数据可以直接观看其可视化形式
data.plot()
plt.show()

data = pd.DataFrame(
    np.random.randn(1000, 4),  # 4列
    index=np.arange(1000),
    columns=list("ABCD")
    )
data = data.cumsum()
data.plot()
plt.show()

ax = data.plot.scatter(x='A',y='B',color='DarkBlue',label='Class1')
bx = data.plot.scatter(x='A', y='D', color='DarkRed', label='Class2', ax=ax)
# 将之下这个 data 画在上一个 ax 上面
data.plot.scatter(x='A',y='C',color='LightGreen',label='Class3',ax=bx)
plt.show()

猜你喜欢

转载自blog.csdn.net/weixin_36926779/article/details/81202473
今日推荐