pandas03

import pandas as pd
import numpy as np
1、检查dataframe是否有缺失值
df = pd.DataFrame({
    'a':[1.2,2,3,4],
    'b':list('abcd')
})
df["a"][1]=np.nan
df.isnull().values.any()
2、统计dataframe中每列缺失值的数量
df.isnull().sum()
3、dataframe用每列的平均值取代缺失值
df.fillna(df.mean())
4、从dataframe中获取某一列, 并返回一个dataframe
df[["a"]].head()
5、dataframe如何改变列的顺序
df[["b","a"]]
6、设置dataframe输出的行数和列数
pd.set_option("display.max_columns",4)
pd.set_option("display.max_row",10)
df
7、设置dataframe输出时不使用科学记数法
pd.set_option("display.float_format",lambda x:"%.4f" % x)
pd.DataFrame({"a":np.random.random(4)})
pd.set_option("display.float_format",None)
8、设置dataframe输出百分比数据
df = pd.DataFrame(np.random.random(4), columns=['random'])
df.style.format({'random':'{0:.2%}'.format})
df
9、使用多个列创建唯一索引(index)
index1=pd.Series([str(x) for x in df["random"]])
index1=index1+"_"+index1
df.index=index1
print(df.index.is_unique)
10、获取第n大的数所在行
df = pd.DataFrame(
    np.random.randint(1, 30, 30).reshape(10,-2), 
    columns=list('abc'))
n=3
df[df["a"]==df.sort_values("a",axis=0,ascending=False).reset_index()["a"][n-1]]

df.ix[df['a'].argsort()[df.shape[0]-n],:]
11、dataframe获取行之和大于100的数据, 并返回最后的两行
df = pd.DataFrame(np.random.randint(10, 40, 60).reshape(-1, 4))
rowsums = df.apply(np.sum, axis=1)
df[rowsums>100].iloc[-2:,:]
12、如何从系列或数据框列中查找和限制异常值

用相应的5%分位数和95%分位数值替换低于5%分位数和大于95%分位数的所有值

se=pd.Series(np.linspace(-2,2,30))
low,high=se.quantile([0.05,0.95])
se[(se>high)|(se<low)]
13、如何在删除负值后将dataframe重新整形为最大可能的正方形

将df重塑为最大可能的正方形,并删除负值。如果需要,删除最小值。结果中正数的顺序应保持与原始顺序相同。

df=pd.DataFrame(np.random.normal(size=[5,5]))
q=df[df>0].values.flatten()
q=q[~np.isnan(q)]
n=int(np.floor(q.shape[0]**0.5))
q=q[:n**2].reshape(n,-1)
14、交换dataframe的两行,把第一行和第二行数据交换
a,b=df.iloc[0,:].copy(),df.iloc[1,:].copy()
df.iloc[0,:],df.iloc[1,:] = b,a
15、dataframe行倒序排序
df.iloc[::-1,:]
16、对分类数据进行one-hot编码,经常用于逻辑回归
df=pd.DataFrame({"fruit":np.random.choice(["apple","bananas","orange"],10),
                 "sales":np.random.randint(4,10,10)})
pd.concat([pd.get_dummies(df["fruit"]),df["sales"]],axis=1)
17、每行最大值所在的列
df = pd.DataFrame(np.random.randint(1,100, 40).reshape(10, -1))
df.apply(np.argmax, axis=1)
18、计算每行的最近行(使用欧几里得距离)
df[0].argsort()
nearest = {}
for i, row in df.iterrows():
    c = ((df - row)**2).sum(axis = 1).argsort()
    nearest[i] = c[1]
print(nearest)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值