转:数据分析打工人的Pandas 75个高频操作

导读:本篇文章讲解 转:数据分析打工人的Pandas 75个高频操作,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

本文分享数据分析中Pandas常用的75个操作~

翻译自:https://www.machinelearningplus.com/python/101-pandas-exercises-python/

notice:原文有多处错误,本文已经debug,可放心食用。


目录

1、pandas导入、查看版本

2、使用python list、python dict、numpy.ndarray创建pandas.Series

3、将pandas.Series转化为pandas.DataFrame

4、将多个pandas.Series合并为一个pandas.DataFrame

5、修改pandas.Series index名称

6、移除pandas.Series1中和pandas.Series2共同的部分

7、求pandas.Series1和pandas.Series2的交集、并集、差集

8、求pandas.Series分位数(最小值、1/4分位数、中位数、3/4分位数、最大值)

9、求pandas.Series()频数

10、输出pandas.Series()中频数排第一二位的、其它的替换为other

11、将pandas.Series()均分为10个区间、每个值使用区间名称标记

12、将pandas.Series()转换为指定shape的pandas.DataFrame

13、取出pandas.Series()中满足条件数据的位置index

14、取出pandas.Series()指定位置的数据

15、pandas.Series()水平、垂直合并

16、输出pandas.Series()子集的index号

17、求真实和预测pd.Series之间的均方误差损失函数(MSE,mean squared error)

18、pd.Series字符串型数据首字母大写转换

19、pd.Series字符串型数据字符长度计算

20、pd.Series中两两数之间差异

21、pd.Series中日期字符串转换为datetime格式

22、获取pd.Series日期字符串中时间对象

23、pd.Series日期字符串中修改为按指定日期输出

24、输出pd.Series中至少包含两个元音字符的数据

25、输出pd.Series中有效的email地址

26、pd.Series1按pd.Series2分组并求均值

27、计算两个pd.Series之间的欧式距离

28、求pd.Series局部峰值index

29、pd.Series字符串数据中使用最低频字符填充空格

30、创建时间序列数据,赋予随机值

31、缺省的时间序列值 不同方式填充

32、找出pd.Series中自相关性最大的数据

33、从一个csv 文件中每间隔50行取数据生成pandas.DataFrame

34、从一个csv 文件取数据生成pandas.DataFrame(新增加一分类列)

35、生成一个按规定步长平移的pandas.DataFrame

36、从一个csv 文件读取指定列生成pandas.DataFrame

37、输出DataFrame的行数、列数、数据类型、类型频数、Series转list

38、输出满足某个规则的DataFrame数据行和列号

39、修改DataFrame的列名称

40、DataFrame中是否有缺省值确认

41、DataFrame中缺省值统计

42、各自列均值填充DataFrame中各自列缺省值

43、各自列均值、中值填充DataFrame中各自列缺省值(使用apply)

44、从DataFrame选择子DataFrame

45、 改变DataFrame列顺序

46、大DataFrame修改默认显示的行和列数

47、DataFrame数据小数位数设置

48、 DataFrame数据小数转百分比显示

49、DataFrame数据每隔20行读取

50、创建DataFrame主键

51、获取DataFrame某一列中第n大的值索引

52、获取DataFrame某一列中第n大的值大于指定值得索引

53、获取DataFrame中行和大于100的行

54、 Series or DataFrame中使用分位数填充超限区域

55、去除指定值将DataFrame转换为最大方阵

56、DataFrame两行交换

57、DataFrame逆序输出

58、DataFrame转对角矩阵

59、DataFrame那一列含有最多行最大值

60、DataFrame创建新列:每行为行号(按欧几里得距离而来)

61、求DataFrame各列之间最大相关系数

62、DataFrame创建一列:包含每行中最小值与最大值比值

64、DataFrame每列按特定方式归一化

65、计算DataFrame每行与后一行的相关系数

66、DataFrame对角线元素替换为0

67、DataFrame按某列分组、提取某个分组

68、DataFrame按另外列分组、提取当前列中指定值(看下方例子,需求不好描述)

69、DataFrame分组(看下方例子,需求不好描述)

70、两个DataFrame使用类似SQL 中INNER JOIN拼接

72、取出DataFrame中两列值相等的行号

73、DataFrame中新建两列:滞后列和提前列(看下方例子,需求BT)

74、DataFrame中所有值出现频次统计

75、拆分DataFrame中某列文本为两列


1、pandas导入、查看版本

#pandas导入

import pandas as pd


#pandas输出版本信息
print(pd.__version__)
#pandas输出详细版本信息、 Python版本、相关程序包、操作系统等信息以json格式输出

print(pd.show_versions(as_json=True))

#pandas输出相关信息以默认格式输出
print(pd.show_versions())

转:数据分析打工人的Pandas 75个高频操作

2、使用python list、python dict、numpy.ndarray创建pandas.Series


  1. import pandas as pd
    
    import numpy as np
    
    mylist = list('abcedfghijklmnopqrstuvwxyz')# python list
    
    myarr = np.arange(26)#numpy.ndarray
    
    mydict = dict(zip(mylist, myarr))#python dict
    
    
    ser1 = pd.Series(mylist)
    
    ser2 = pd.Series(myarr)
    
    ser3 = pd.Series(mydict)
    
    print(ser1.head(2))
    
    print(ser2.head(2))
    
    print(ser3.head(2))

转:数据分析打工人的Pandas 75个高频操作

3、将pandas.Series转化为pandas.DataFrame

需求:转:数据分析打工人的Pandas 75个高频操作解决:


mylist = list('abcedfghijklmnopqrstuvwxyz')

myarr = np.arange(26)

mydict = dict(zip(mylist, myarr))

ser = pd.Series(mydict)


#to_frame()结合reset_index()使用

df = ser.to_frame().reset_index()

print(df.head())

转:数据分析打工人的Pandas 75个高频操作

4、将多个pandas.Series合并为一个pandas.DataFrame


  1. # 输入
    
    import numpy as np
    
    ser1 = pd.Series(list('abcedfghijklmnopqrstuvwxyz'))
    ser2 = pd.Series(np.arange(26))
    
    # 解决方法1
    df = pd.concat([ser1, ser2], axis=1)
    
    # 解决方法2
    df = pd.DataFrame({'col1': ser1, 'col2': ser2})
    print(df.head())
    
    
    ## 5、修改pandas.Series index名称
    ![](https://img-blog.csdnimg.cn/20210112110008299.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIxNDc4MjYx,size_16,color_FFFFFF,t_70)
    
    
    ## 6、 移除pandas.Series1中和pandas.Series2共同的部分
    
    
    ```python
    
    ser1 = pd.Series([1, 2, 3, 4, 5])
    ser2 = pd.Series([4, 5, 6, 7, 8])
    ser1[~ser1.isin(ser2)]

转:数据分析打工人的Pandas 75个高频操作

7、求pandas.Series1和pandas.Series2共的交集、并集、差集


ser1 = pd.Series([1, 2, 3, 4, 5])

ser2 = pd.Series([4, 5, 6, 7, 8])


ser_u = pd.Series(np.union1d(ser1, ser2))  # union

ser_i = pd.Series(np.intersect1d(ser1, ser2))  # intersect

ser_s = ser_u[~ser_u.isin(ser_i)]# Subtraction


print("交集")

print(ser_i)


print("并集")

print(ser_u)


print("差集")

print(ser_s)

转:数据分析打工人的Pandas 75个高频操作

8、求pandas.Series分位数(最小值、1/4分位数、中位数、3/4分位数、最大值)


  1. state = np.random.RandomState(100)

  2. ser = pd.Series(state.normal(10, 5, 25))

  3. np.percentile(ser, q=[0, 25, 50, 75, 100])#可是设置其它任何想输出的分位数

转:数据分析打工人的Pandas 75个高频操作

9、求pandas.Series()频数


  1. ser = pd.Series(np.take(list('abcdefgh'), np.random.randint(8, size=30)))

  2. ser.value_counts()

转:数据分析打工人的Pandas 75个高频操作

10、输出pandas.Series()中频数排第一二位的、其它的替换为other


  1. np.random.RandomState(100)

  2. ser = pd.Series(np.random.randint(1, 5, [12]))

  3. print("Top 2 Freq:", ser.value_counts())

  4. ser[~ser.isin(ser.value_counts().index[:2])] = 'Other'

  5. ser

转:数据分析打工人的Pandas 75个高频操作

11、将pandas.Series()均分为10个区间、每个值使用区间名称标记


  1. np.random.seed(666)  #让结果可重复

  2. ser = pd.Series(np.random.random(20))

  3. print(ser.head())

  4. pd.qcut(ser,

  5.         q=[0, .10, .20, .3, .4, .5, .6, .7, .8, .9, 1],

  6.         labels=[

  7.             '1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th',

  8.             '10th'

  9.         ])

转:数据分析打工人的Pandas 75个高频操作

12、将pandas.Series()转换为指定shape的pandas.DataFrame


  1. ser = pd.Series(np.random.randint(1, 10, 35))

  2. df = pd.DataFrame(ser.values.reshape(7,5))

  3. print(df)

转:数据分析打工人的Pandas 75个高频操作

13、取出pandas.Series()中满足条件数据的位置index


  1. np.random.seed(666) 

  2. ser = pd.Series(np.random.randint(1, 10, 7))

  3. print(ser)

  4. np.argwhere(ser.values % 3 == 0)#数据为3的倍数的数据

转:数据分析打工人的Pandas 75个高频操作

14、取出pandas.Series()指定位置的数据


  1. ser = pd.Series(list('abcdefghijklmnopqrstuvwxyz'))

  2. pos = [0, 4, 8, 14, 20]#待取出位置

  3. ser.take(pos)

转:数据分析打工人的Pandas 75个高频操作

15、pandas.Series()水平、垂直合并


  1. ser1 = pd.Series(range(5))

  2. ser2 = pd.Series(list('abcde'))

  3. # 垂直合并

  4. ser3 = ser1.append(ser2)

  5. print(ser3)

  6. # 水平合并

  7. df = pd.concat([ser1, ser2], axis=1)

  8. print(df)

转:数据分析打工人的Pandas 75个高频操作

16、输出pandas.Series()子集的index号


  1. 获取ser2在ser1中的index号

  2. ser1 = pd.Series([10, 9, 6, 5, 3, 1, 12, 8, 13])

  3. ser2 = pd.Series([1, 3, 10, 13])

  4. # 方法1

  5. [np.where(i == ser1)[0].tolist()[0] for i in ser2]

  6. # 方法2

  7. [pd.Index(ser1).get_loc(i) for i in ser2]

转:数据分析打工人的Pandas 75个高频操作

17、求真实和预测pd.Series之间的均方误差损失函数(MSE,mean squared error)


  1. truth = pd.Series(range(10))

  2. pred = pd.Series(range(10)) + np.random.random(10)

  3. np.mean((truth-pred)**2)

转:数据分析打工人的Pandas 75个高频操作

18、pd.Series字符串型数据首字母大写转换


  1. ser = pd.Series(['how', 'to', 'kick', 'ass?'])

  2. # 方法一title()结合title()

  3. ser.map(lambda x: x.title())

  4. # 方法二upper()结合lambda

  5. ser.map(lambda x: x[0].upper() + x[1:])

  6. # 方法三title()结合列表推导式

  7. pd.Series([i.title() for i in ser])

转:数据分析打工人的Pandas 75个高频操作

19、pd.Series字符串型数据字符长度计算


  1. ser = pd.Series(['how', 'to', 'kick', 'ass?'])

  2. ser.map(lambda x: len(x))

转:数据分析打工人的Pandas 75个高频操作

20、pd.Series中两两数之间差异


  1. ser = pd.Series([1, 3, 6, 10, 15, 21, 27, 35])

  2. print(ser.diff().tolist())

转:数据分析打工人的Pandas 75个高频操作

21、pd.Series中日期字符串转换为datetime格式


  1. ser = pd.Series(['01 Jan 2010', '02-02-2011', '20120303', '2013/04/04', '2014-05-05', '2015-06-06T12:20'])

  2. # 方法一

  3. from dateutil.parser import parse

  4. ser.map(lambda x: parse(x))

  5. # 方法二

  6. pd.to_datetime(ser)

转:数据分析打工人的Pandas 75个高频操作

22、获取pd.Series日期字符串中时间对象


  1. ser = pd.Series(['01 Jan 2011', '02-02-2011', '20120303', '2013/04/04', '2014-05-05', '2015-06-06T12:20'])

  2. from dateutil.parser import parse

  3. ser_ts = ser.map(lambda x: parse(x))

  4. # 处于该月中的那一天

  5. print("Date: ", ser_ts.dt.day.tolist())

  6. # week number

  7. print("Week number: ", ser_ts.dt.weekofyear.tolist())

  8. # 处于该年的第多少天

  9. print("Day number of year: ", ser_ts.dt.dayofyear.tolist())

  10. # 处于该年周几

  11. print("Day of week: ", ser_ts.dt.day_name().tolist())#pythonic生物人修改,原文ser_ts.dt.weekday_name.tolist()有误

转:数据分析打工人的Pandas 75个高频操作

23、pd.Series日期字符串中修改为按指定日期输出


  1. import pandas as pd

  2. ser = pd.Series(['Jan 2010', 'Feb 2011', 'Mar 2012'])

  3. # 方法1

  4. from dateutil.parser import parse

  5. # Parse the date

  6. ser_ts = ser.map(lambda x: parse(x))

  7. # Construct date string with date as 4

  8. ser_datestr = ser_ts.dt.year.astype('str') + '-' + ser_ts.dt.month.astype('str') + '-' + '04'

  9. # Format it.

  10. [parse(i).strftime('%Y-%m-%d') for i in ser_datestr]

  11. # 方法2

  12. ser.map(lambda x: parse('04 ' + x))

转:数据分析打工人的Pandas 75个高频操作

24、输出pd.Series中至少包含两个元音字符的数据


  1. ser = pd.Series(['Apple', 'Orange', 'Plan', 'Python', 'Money'])

  2. from collections import Counter

  3. mask = ser.map(lambda x: sum([Counter(x.lower()).get(i, 0) for i in list('aeiou')]) >= 2)

  4. ser[mask]

转:数据分析打工人的Pandas 75个高频操作

25、输出pd.Series中有效的email地址


  1. # 三种方法

  2. emails = pd.Series(['buying books at amazom.com', 'rameses@egypt.com', 'matt@t.co', 'narendra@modi.com'])

  3. # Solution 1 (as series of strings)

  4. import re

  5. pattern ='[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}'

  6. mask = emails.map(lambda x: bool(re.match(pattern, x)))

  7. emails[mask]

  8. # Solution 2 (as series of list)

  9. emails.str.findall(pattern, flags=re.IGNORECASE)

  10. # Solution 3 (as list)

  11. [x[0] for x in [re.findall(pattern, email) for email in emails] if len(x) > 0]

26、pd.Series1按pd.Series2分组并求均值


  1. fruit = pd.Series(np.random.choice(['apple', 'banana', 'carrot'], 10))

  2. weights = pd.Series(np.linspace(1, 10, 10))

  3. weights.groupby(fruit).mean()

转:数据分析打工人的Pandas 75个高频操作

27、计算两个pd.Series之间的欧式距离


  1. p = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

  2. q = pd.Series([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])

  3. # 方法1 

  4. sum((p - q)**2)**.5

  5. # 方法2

  6. np.linalg.norm(p-q)

转:数据分析打工人的Pandas 75个高频操作

28、求pd.Series局部峰值index


  1. ser = pd.Series([2, 10, 3, 4, 9, 10, 2, 7, 3])

  2. dd = np.diff(np.sign(np.diff(ser)))

  3. peak_locs = np.where(dd == -2)[0] + 1

  4. peak_locs

转:数据分析打工人的Pandas 75个高频操作

29、pd.Series字符串数据中使用最低频字符填充空格


  1. my_str = 'dbc deb abed gade'

  2. ser = pd.Series(list('dbc deb abed gade'))

  3. freq = ser.value_counts()

  4. print(freq)

  5. least_freq = freq.dropna().index[-1]

  6. "".join(ser.replace(' ', least_freq))

转:数据分析打工人的Pandas 75个高频操作

30、创建时间序列数据,赋予随机值


  1. ser = pd.Series(np.random.randint(1,10,10), pd.date_range('2000-01-01', periods=10, freq='W-SAT'))

  2. ser

转:数据分析打工人的Pandas 75个高频操作

31、缺省的时间序列值 不同方式填充


  1. ser = pd.Series([1,10,3, np.nan], index=pd.to_datetime(['2000-01-01', '2000-01-03', '2000-01-06', '2000-01-08']))

  2. ser.resample('D').ffill()  # 前填充

  3. ser.resample('D').bfill()  # f后填充

  4. ser.resample('D').bfill().ffill()  # 先后填充,如后无值则前填充

转:数据分析打工人的Pandas 75个高频操作

32、找出pd.Series中自相关性最大的数据


  1. ser = pd.Series(np.arange(20) + np.random.normal(1, 10, 20))

  2. autocorrelations = [ser.autocorr(i).round(2) for i in range(11)]

  3. print(autocorrelations[1:])

  4. print('Lag having highest correlation: ', np.argmax(np.abs(autocorrelations[1:]))+1)

转:数据分析打工人的Pandas 75个高频操作

33、从一个csv 文件中每间隔50行取数据生成pandas.DataFrame


  1. #三种方法

  2. # Solution 1: Use chunks and for-loop

  3. df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv', chunksize=50)

  4. df2 = pd.DataFrame()

  5. for chunk in df:

  6.     df2 = df2.append(chunk.iloc[0,:])

  7. # Solution 2: Use chunks and list comprehension

  8. df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv', chunksize=50)

  9. df2 = pd.concat([chunk.iloc[0] for chunk in df], axis=1)

  10. df2 = df2.transpose()

  11. # Solution 3: Use csv reader

  12. import csv          

  13. with open('BostonHousing.csv', 'r') as f:

  14.     reader = csv.reader(f)

  15.     out = []

  16.     for i, row in enumerate(reader):

  17.         if i%50 == 0:

  18.             out.append(row)

转:数据分析打工人的Pandas 75个高频操作

34、从一个csv 文件取数据生成pandas.DataFrame(新增加一分类列)


  1. ##两种方式

  2. # Solution 1: Using converter parameter

  3. df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv', 

  4.                  converters={'medv': lambda x: 'High' if float(x) > 25 else 'Low'})

  5. # Solution 2: Using csv reader

  6. import csv

  7. with open('BostonHousing.csv', 'r') as f:

  8.     reader = csv.reader(f)

  9.     out = []

  10.     for i, row in enumerate(reader):

  11.         if i > 0:

  12.             row[13] = 'High' if float(row[13]) > 25 else 'Low'

  13.         out.append(row)

  14. df = pd.DataFrame(out[1:], columns=out[0])

  15. print(df.head())

转:数据分析打工人的Pandas 75个高频操作

35、生成一个按规定步长平移的pandas.DataFrame


  1. L = pd.Series(range(15))

  2. def gen_strides(a, stride_len=5, window_len=5):

  3.     n_strides = ((a.size-window_len)//stride_len) + 1

  4.     return np.array([a[s:(s+window_len)] for s in np.arange(0, a.size, stride_len)[:n_strides]])

  5. gen_strides(L, stride_len=2, window_len=4)

转:数据分析打工人的Pandas 75个高频操作

36、从一个csv 文件读取指定列生成pandas.DataFrame


  1. #usecols参数设置

  2. df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv', usecols=['crim', 'medv'])

  3. print(df.head())

转:数据分析打工人的Pandas 75个高频操作

37、输出DataFrame的行数、列数、数据类型、类型频数、Series转list


  1. import pandas as pd

  2. #https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv

  3. df = pd.read_csv('./Cars93_miss.csv')

  4. #  DataFrame的行数和列数

  5. print(df.shape)

  6. # DataFrame各列数据类型

  7. print(df.dtypes.head())

  8. # 每种数据类型的频数

  9. print(df.dtypes.value_counts())

  10. # DataFrame基础统计

  11. df_stats = df.describe()

  12. # pd.Series转list 

  13. df['Model'].tolist()[0]

转:数据分析打工人的Pandas 75个高频操作

38、输出满足某个规则的DataFrame数据行和列号


  1. df = pd.read_csv('./Cars93_miss.csv')

  2. #输出Price值最大时的行和列号

  3. row, col = np.where(df.values == np.max(df.Price))#df.values输出DataFrame的值,为numpy.ndarray类型

  4. print('%s\t%s'%(row,col))

转:数据分析打工人的Pandas 75个高频操作

39、修改DataFrame的列名称


  1. #修改某一列的名称

  2. df=df.rename(columns = {'Type':'CarType'})

  3. # 或者

  4. #df.columns.values[2] = "CarType"

  5. # map函数修改某一匹配的名称:此处将名称中的.替换为下划线

  6. df.columns = df.columns.map(lambda x: x.replace('.', '_'))

  7. df.columns

转:数据分析打工人的Pandas 75个高频操作

40、DataFrame中是否有缺省值确认


  1. df = pd.read_csv('./Cars93_miss.csv')

  2. df.isnull().values.any()

转:数据分析打工人的Pandas 75个高频操作

41、DataFrame中缺省值统计


  1. n_missings_each_col = df.apply(lambda x: x.isnull().sum())#每列缺省值计数

  2. print(n_missings_each_col)

  3. n_missings_each_col.argmax()#缺省值数最多列的列号

转:数据分析打工人的Pandas 75个高频操作

42、各自列均值填充DataFrame中各自列缺省值


  1. df = pd.read_csv('./Cars93_miss.csv')

  2. df_out = df[['Min.Price', 'Max.Price']] = df[['Min.Price', 'Max.Price']].apply(lambda x: x.fillna(x.mean()))

  3. print(df_out.head())

43、各自列均值、中值填充DataFrame中各自列缺省值(使用apply)


  1. df = pd.read_csv('./Cars93_miss.csv')

  2. d = {'Min.Price': np.nanmean, 'Max.Price': np.nanmedian}

  3. df[['Min.Price', 'Max.Price']] = df[['Min.Price', 'Max.Price']].apply(lambda x, d: x.fillna(d[x.name](x)), args=(d, ))

44、从DataFrame选择子DataFrame


  1. df = pd.DataFrame(np.arange(20).reshape(-1, 5), columns=list('abcde'))

  2. # 选择子DataFrame

  3. type(df[['a']])

  4. type(df.loc[:, ['a']])

  5. type(df.iloc[:, [0]])

  6. # 选择Series

  7. type(df.a)

  8. type(df['a'])

  9. type(df.loc[:, 'a'])

  10. type(df.iloc[:, 1])

45、 改变DataFrame列顺序


  1. import numpy as np

  2. df = pd.DataFrame(np.arange(20).reshape(-1, 5), columns=list('abcde'))

  3. # 方法1:传入一个list

  4. df[list('cbade')]

  5. # 方法2:自定义函数

  6. def switch_columns(df, col1=None, col2=None):

  7.     colnames = df.columns.tolist()

  8.     i1, i2 = colnames.index(col1), colnames.index(col2)

  9.     colnames[i2], colnames[i1] = colnames[i1], colnames[i2]

  10.     return df[colnames]

  11. df1 = switch_columns(df, 'a', 'c')

  12. # 方法3:

  13. df[sorted(df.columns)]

  14. # 方法4:

  15. df.sort_index(axis=1, ascending=False, inplace=True)

46、大DataFrame修改默认显示的行和列数


  1. df = pd.read_csv('./Cars93_miss.csv.txt')

  2. pd.set_option('display.max_columns', 10)#输出10列

  3. pd.set_option('display.max_rows', 10)#输出10行

  4. df

47、DataFrame数据小数位数设置


  1. df = pd.DataFrame(np.random.random(4)**10, columns=['random'])

  2. #方法1: Rounding

  3. df.round(4)

  4. #方法2: Use apply to change format

  5. df.apply(lambda x: '%.4f' % x, axis=1)

  6. # or

  7. df.applymap(lambda x: '%.4f' % x)

  8. #方法3: Use set_option

  9. pd.set_option('display.float_format', lambda x: '%.4f' % x)

  10. #方法4: Assign display.float_format

  11. pd.options.display.float_format = '{:.4f}'.format

  12. print(df)

48、 DataFrame数据小数转百分比显示


  1. df = pd.DataFrame(np.random.random(4), columns=['random'])

  2. out = df.style.format({

  3.     'random': '{0:.2%}'.format,

  4. })

49、DataFrame数据每隔20行读取


  1. df = pd.read_csv('./Cars93_miss.csv.txt')

  2. print(df.iloc[::20, :][['Manufacturer', 'Model', 'Type']])

转:数据分析打工人的Pandas 75个高频操作

50、创建DataFrame主键


  1. df = pd.read_csv('./Cars93_miss.csv', usecols=[0,1,2,3,5])

  2. df[['Manufacturer', 'Model', 'Type']] = df[['Manufacturer', 'Model', 'Type']].fillna('missing')

  3. df.index = df.Manufacturer + '_' + df.Model + '_' + df.Type

  4. print(df.index.is_unique)

51、获取DataFrame某一列中第n大的值索引


  1. df = pd.DataFrame(np.random.randint(1, 30, 30).reshape(10,-1), columns=list('abc'))

  2. n = 5#第5大

  3. df['a'].argsort()[::-1][n]

52、获取DataFrame某一列中第n大的值大于指定值得索引


  1. ser = pd.Series(np.random.randint(1, 100, 15))

  2. print('ser: ', ser.tolist(), 'mean: ', round(ser.mean()))

  3. np.argwhere(ser > ser.mean())[1]

转:数据分析打工人的Pandas 75个高频操作

53、获取DataFrame中行和大于100的行


  1. df = pd.DataFrame(np.random.randint(10, 40, 60).reshape(-1, 4))

  2. # 求行和

  3. rowsums = df.apply(np.sum, axis=1)#axis=1指定行

  4. df.iloc[np.where(rowsums > 100)]

转:数据分析打工人的Pandas 75个高频操作

54、 Series or DataFrame中使用分位数填充超限区域


  1. #需求:使用0.05分位数和0.95分位数分别替换小于和大于该分位数的区域

  2. ser = pd.Series(np.logspace(-2, 2, 30))

  3. def cap_outliers(ser, low_perc, high_perc):

  4.     low, high = ser.quantile([low_perc, high_perc])#指定分位数

  5.     print(low_perc, '%ile: ', low, '|', high_perc, '%ile: ', high)

  6.     ser[ser < low] = low

  7.     ser[ser > high] = high

  8.     return(ser)

  9. capped_ser = cap_outliers(ser, .05, .95)

55、去除指定值将DataFrame转换为最大方阵


  1. df = pd.DataFrame(np.random.randint(-20, 50, 100).reshape(10,-1))

  2. print(df)

  3. #去除负值

  4. arr = df[df > 0].values.flatten()

  5. arr_qualified = arr[~np.isnan(arr)]

  6. #寻找最大可能的方阵维度

  7. n = int(np.floor(arr_qualified.shape[0]**.5))

  8. #方阵转换

  9. top_indexes = np.argsort(arr_qualified)[::-1]

  10. output = np.take(arr_qualified, sorted(top_indexes[:n**2])).reshape(n, -1)

  11. print(output)

转:数据分析打工人的Pandas 75个高频操作

56、DataFrame两行交换


  1. df = pd.DataFrame(np.arange(25).reshape(5, -1))

  2. def swap_rows(df, i1, i2):

  3.     a, b = df.iloc[i1, :].copy(), df.iloc[i2, :].copy()

  4.     df.iloc[i1, :], df.iloc[i2, :] = b, a

  5.     return df

  6. print(swap_rows(df, 1, 2))

转:数据分析打工人的Pandas 75个高频操作

57、DataFrame逆序输出


  1. df = pd.DataFrame(np.arange(25).reshape(5, -1))

  2. print(df)

  3. #方法 1

  4. df.iloc[::-1, :]

  5. #方法 2

  6. print(df.loc[df.index[::-1], :])

转:数据分析打工人的Pandas 75个高频操作

58、DataFrame转对角矩阵


  1. df = pd.DataFrame(np.arange(25).reshape(5,-1), columns=list('abcde'))

  2. print(df)

  3. df_onehot = pd.concat([pd.get_dummies(df['a']), df[list('bcde')]], axis=1)

  4. print(df_onehot)

转:数据分析打工人的Pandas 75个高频操作

59、DataFrame那一列含有最多行最大值


  1. df = pd.DataFrame(np.random.randint(1,100, 40).reshape(10, -1))

  2. print(df)

  3. print('Column with highest row maxes: ', df.apply(np.argmax, axis=1).value_counts().index[0])

转:数据分析打工人的Pandas 75个高频操作

60、DataFrame创建新列:每行为行号(按欧几里得距离而来)


  1. df = pd.DataFrame(np.random.randint(1,100, 40).reshape(10, -1), columns=list('pqrs'), index=list('abcdefghij'))

  2. print(df)

  3. import numpy as np

  4. # init outputs

  5. nearest_rows = []

  6. nearest_distance = []

  7. # iterate rows.

  8. for i, row in df.iterrows():

  9.     curr = row

  10.     rest = df.drop(i)

  11.     e_dists = {}  # init dict to store euclidean dists for current row.

  12.     # iterate rest of rows for current row

  13.     for j, contestant in rest.iterrows():

  14.         # compute euclidean dist and update e_dists

  15.         e_dists.update({j: round(np.linalg.norm(curr.values - contestant.values))})

  16.     # update nearest row to current row and the distance value

  17.     nearest_rows.append(max(e_dists, key=e_dists.get))

  18.     nearest_distance.append(max(e_dists.values()))

  19. df['nearest_row'] = nearest_rows

  20. df['dist'] = nearest_distance

  21. df

转:数据分析打工人的Pandas 75个高频操作

61、求DataFrame各列之间「最大」相关系数


  1. df = pd.DataFrame(np.random.randint(1,100, 80).reshape(8, -1), columns=list('pqrstuvwxy'), index=list('abcdefgh'))

  2. print(df)

  3. abs_corrmat = np.abs(df.corr())

  4. max_corr = abs_corrmat.apply(lambda x: sorted(x)[-2])

  5. print('Maximum Correlation possible for each column: ', np.round(max_corr.tolist(), 2))

转:数据分析打工人的Pandas 75个高频操作

62、DataFrame创建一列:包含每行中最小值与最大值比值


  1. df = pd.DataFrame(np.random.randint(1,100, 80).reshape(8, -1))

  2. print(df)

  3. #方法 1

  4. min_by_max = df.apply(lambda x: np.min(x)/np.max(x), axis=1)

  5. #方法 2

  6. min_by_max = np.min(df, axis=1)/np.max(df, axis=1)

  7. min_by_max

转:数据分析打工人的Pandas 75个高频操作

63、DataFrame创建一列:包含每行中第二大的值


  1. df = pd.DataFrame(np.random.randint(1,100, 80).reshape(8, -1))

  2. out = df.apply(lambda x: x.sort_values().unique()[-2], axis=1)

  3. df['penultimate'] = out

  4. df

转:数据分析打工人的Pandas 75个高频操作

64、DataFrame每列按特定方式归一化


  1. df = pd.DataFrame(np.random.randint(1,100, 80).reshape(8, -1))

  2. # 均值、标准差归一化

  3. out1 = df.apply(lambda x: ((x - x.mean())/x.std()).round(2))

  4. print('均值、标准差归一化:\n',out1)

  5. # 最大最小值归一化

  6. out2 = df.apply(lambda x: ((x.max() - x)/(x.max() - x.min())).round(2))

  7. print('最大最小值归一化:\n', out2)  

转:数据分析打工人的Pandas 75个高频操作

65、计算DataFrame每行与后一行的相关系数


  1. df = pd.DataFrame(np.random.randint(1,100, 80).reshape(8, -1))

  2. [df.iloc[i].corr(df.iloc[i+1]).round(2) for i in range(df.shape[0])[:-1]]

转:数据分析打工人的Pandas 75个高频操作

66、DataFrame对角线元素替换为0


  1. df = pd.DataFrame(np.random.randint(1,100, 100).reshape(10, -1))

  2. print(df)

  3. for i in range(df.shape[0]):

  4.     df.iat[i, i] = 0

  5.     df.iat[df.shape[0]-i-1, i] = 0

  6.     

  7. df

转:数据分析打工人的Pandas 75个高频操作

67、DataFrame按某列分组、提取某个分组


  1. df = pd.DataFrame({'col1': ['apple', 'banana', 'orange'] * 3,

  2.                    'col2': np.random.rand(9),

  3.                    'col3': np.random.randint(0, 15, 9)})

  4. print(df)

  5. df_grouped = df.groupby(['col1'])#按col1列分组

  6. #获取指定分组,此处取apple组

  7. # 方法 1

  8. df_grouped.get_group('apple')

  9. # 方法 2

  10. for i, dff in df_grouped:

  11.     if i == 'apple':

  12.         print(dff)

转:数据分析打工人的Pandas 75个高频操作

68、DataFrame按另外列分组、提取当前列中指定值(看下方例子,需求不好描述)


  1. df = pd.DataFrame({'fruit': ['apple', 'banana', 'orange'] * 3,

  2.                    'taste': np.random.rand(9),

  3.                    'price': np.random.randint(0, 15, 9)})

  4. print(df)

  5. df_grpd = df['taste'].groupby(df.fruit)#taste值按fruit类别排序

  6. df_grpd.get_group('banana').sort_values().iloc[-2]#获取fruit中的banana组,取第二大值

转:数据分析打工人的Pandas 75个高频操作

69、DataFrame分组(看下方例子,需求不好描述)


  1. df = pd.DataFrame({'fruit': ['apple', 'banana', 'orange'] * 3,

  2.                    'rating': np.random.rand(9),

  3.                    'price': np.random.randint(0, 15, 9)})

  4. print(df)

  5. out = df.groupby('fruit', as_index=False)['price'].mean()#按fruit分组、求每类fruit的均价

  6. print(out)

转:数据分析打工人的Pandas 75个高频操作

70、两个DataFrame使用类似SQL 中INNER JOIN拼接


  1. # Join dataframes df1 and df2 by ‘fruit-pazham’ and ‘weight-kilo’.

  2. df1 = pd.DataFrame({

  3.     'fruit': ['apple', 'banana', 'orange'] * 3,

  4.     'weight': ['high', 'medium', 'low'] * 3,

  5.     'price': np.random.randint(0, 15, 9)

  6. })

  7. df2 = pd.DataFrame({

  8.     'pazham': ['apple', 'orange', 'pine'] * 2,

  9.     'kilo': ['high', 'low'] * 3,

  10.     'price': np.random.randint(0, 15, 6)

  11. })

  12. print('df1:\n')

  13. print(df1)

  14. print('df2:\n')

  15. print(df2)

  16. # Solution

  17. pd.merge(df1,

  18.          df2,

  19.          how='inner',

  20.          left_on=['fruit', 'weight'],

  21.          right_on=['pazham', 'kilo'],

  22.          suffixes=['_left', '_right'])

转:数据分析打工人的Pandas 75个高频操作

71、移除DataFrame1中在DataFrame2出现的行


  1. df1 = pd.DataFrame({

  2.     'fruit': ['apple', 'orange', 'banana'] * 3,

  3.     'weight': ['high', 'medium', 'low'] * 3,

  4.     'price': np.arange(9)

  5. })

  6. df2 = pd.DataFrame({

  7.     'fruit': ['apple', 'orange', 'pine'] * 2,

  8.     'weight': ['high', 'medium'] * 3,

  9.     'price': np.arange(6)

  10. })

  11. print('df1:\n')

  12. print(df1)

  13. print('df2:\n')

  14. print(df2)

  15. print(df1[~df1.isin(df2).all(1)])

转:数据分析打工人的Pandas 75个高频操作

72、取出DataFrame中两列值相等的行号


  1. df = pd.DataFrame({

  2.     'fruit1': np.random.choice(['apple', 'orange', 'banana'], 10),

  3.     'fruit2': np.random.choice(['apple', 'orange', 'banana'], 10)

  4. })

  5. print(df)

  6. np.where(df.fruit1 == df.fruit2)

转:数据分析打工人的Pandas 75个高频操作

73、DataFrame中新建两列:滞后列和提前列(看下方例子,需求BT)


  1. df = pd.DataFrame(np.random.randint(1, 100, 20).reshape(-1, 4),

  2.                   columns=list('abcd'))

  3. print(df)

  4. df['a_lag1'] = df['a'].shift(1)#a列每行值向后移一位

  5. df['b_lead1'] = df['b'].shift(-1)#b列每行值向前移一位

  6. print(df)

转:数据分析打工人的Pandas 75个高频操作

74、DataFrame中所有值出现频次统计


  1. df = pd.DataFrame(np.random.randint(1, 10, 20).reshape(-1, 4),

  2.                   columns=list('abcd'))

  3. pd.value_counts(df.values.ravel())

转:数据分析打工人的Pandas 75个高频操作

75、拆分DataFrame中某列文本为两列


  1. df = pd.DataFrame([

  2.     "STD, City    State", "33, Kolkata    West Bengal",

  3.     "44, Chennai    Tamil Nadu", "40, Hyderabad    Telengana",

  4.     "80, Bangalore    Karnataka"

  5. ],

  6.                   columns=['row'])

  7. print(df)

  8. df_out = df.row.str.split(',|\t', expand=True)#拆分

  9. new_header = df_out.iloc[0]#第一列设置为标题

  10. df_out = df_out[1:]

  11. df_out.columns = new_header

  12. print(df_out)

转:数据分析打工人的Pandas 75个高频操作

–END-

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/101586.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!