pandas练习_____

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = {"grammer":["Python","C","Java","GO",np.nan,"SQL","PHP","Python"],
       "score":[1,2,np.nan,4,5,6,7,10]}
data
{'grammer': ['Python', 'C', 'Java', 'GO', nan, 'SQL', 'PHP', 'Python'],
 'score': [1, 2, nan, 4, 5, 6, 7, 10]}
df = pd.DataFrame(data)
df
grammerscore
0Python1.0
1C2.0
2JavaNaN
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
7Python10.0

3提取含有字符串"Python"的行

df['grammer'] == 'Python'
0     True
1    False
2    False
3    False
4    False
5    False
6    False
7     True
Name: grammer, dtype: bool
df[df['grammer'] == 'Python']
grammerscore
0Python1.0
7Python10.0
df.columns
Index(['grammer', 'score'], dtype='object')

4.修改第二列列名为’popularity’

df.rename(columns={"score":"popularity"},inplace=True)
df
grammerpopularity
0Python1.0
1C2.0
2JavaNaN
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
7Python10.0

5.统计grammer列中每种编程语言出现的次数

df["grammer"].value_counts()
Python    2
C         1
Java      1
PHP       1
SQL       1
GO        1
Name: grammer, dtype: int64
df1 = df.copy()
df2 = df.copy()
df1
grammerpopularity
0Python1.0
1C2.0
2JavaNaN
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
7Python10.0

6,将空值用上下值的平均值填充

df1['popularity'] = df1['popularity'].fillna(df1['popularity'].interpolate())
df1
grammerpopularity
0Python1.0
1C2.0
2Java3.0
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
7Python10.0
### 把0值替换为na的方法:df.replace(0,np.nan)
df2.iloc[:,1] = df2.iloc[:,1].fillna(df2.iloc[:,1].interpolate())
df2
grammerpopularity
0Python1.0
1C2.0
2Java3.0
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
7Python10.0
df
grammerpopularity
0Python1.0
1C2.0
2JavaNaN
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
7Python10.0
df["popularity"].fillna(df["popularity"].interpolate(),inplace=True)
df
grammerpopularity
0Python1.0
1C2.0
2Java3.0
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
7Python10.0

保留popularity列大于3的值

df[df.iloc[:,1]>3]
grammerpopularity
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
7Python10.0

去除grammar列 重复值

df.drop_duplicates("grammer",inplace = True)
df
grammerpopularity
0Python1.0
1C2.0
2Java3.0
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
df["popularity"].mean()
4.0

10,将grammer列转换为list

df["grammer"].to_list()
['Python', 'C', 'Java', 'GO', nan, 'SQL', 'PHP']

11.将DataFrame保存为EXCEL

df.to_csv("./test.csv")
df.to_excel('test.xlsx',index=False)
df[(df["popularity"]>3) & (df["popularity"]<7)]
grammerpopularity
3GO4.0
4NaN5.0
5SQL6.0

14.交换两列位置

cols = df.columns[[1,0]]
cols
Index(['popularity', 'grammer'], dtype='object')
cols_1 = df.columns[[0,1]]
cols_1
Index(['grammer', 'popularity'], dtype='object')
type(cols_1)
pandas.core.indexes.base.Index
df = df[cols]
df
popularitygrammer
01.0Python
12.0C
23.0Java
34.0GO
45.0NaN
56.0SQL
67.0PHP
### 方法2
temp = df['popularity']
df.drop(labels=['popularity'], axis=1,inplace = True)
df.insert(0, 'popularity', temp)
df
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\pandas\core\frame.py:4167: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  errors=errors,
popularitygrammer
01.0Python
12.0C
23.0Java
34.0GO
45.0NaN
56.0SQL
67.0PHP

15.提取popularity列最大值所在行

df["popularity"] == df["popularity"].max() 
0    False
1    False
2    False
3    False
4    False
5    False
6     True
Name: popularity, dtype: bool
df[df["popularity"] == df["popularity"].max() ]
popularitygrammer
67.0PHP

16查看最后五行

df.tail()
popularitygrammer
23.0Java
34.0GO
45.0NaN
56.0SQL
67.0PHP
df
popularitygrammer
01.0Python
12.0C
23.0Java
34.0GO
45.0NaN
56.0SQL
67.0PHP

17 删掉一行,一列

df.drop("popularity",axis=1)
grammer
0Python
1C
2Java
3GO
4NaN
5SQL
6PHP
df.drop(6,axis=0)
popularitygrammer
01.0Python
12.0C
23.0Java
34.0GO
45.0NaN
56.0SQL

18.添加一行数据[‘Perl’,6.6]

df.columns[[1,0]]
Index(['grammer', 'popularity'], dtype='object')
df = df[df.columns[[1,0]]]
df
grammerpopularity
0Python1.0
1C2.0
2Java3.0
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
a = {"grammer":"perl","popularity":6.6}
df.append(a,ignore_index=True)
grammerpopularity
0Python1.0
1C2.0
2Java3.0
3GO4.0
4NaN5.0
5SQL6.0
6PHP7.0
7perl6.6

添加一列数据

a = "grammar" ## 新的列名
a
'grammar'
b = df["grammer"]
b
0    Python
1         C
2      Java
3        GO
4       NaN
5       SQL
6       PHP
Name: grammer, dtype: object
df.insert(0,a,b) # 插入的位置, 列名 ,内容
df
grammargrammerpopularity
0PythonPython1.0
1CC2.0
2JavaJava3.0
3GOGO4.0
4NaNNaN5.0
5SQLSQL6.0
6PHPPHP7.0

19.对数据按照"popularity"列值的大小进行排序

df["popularity"].sort_values()
0    1.0
1    2.0
2    3.0
3    4.0
4    5.0
5    6.0
6    7.0
Name: popularity, dtype: float64
df.sort_values("popularity")
grammargrammerpopularity
0PythonPython1.0
1CC2.0
2JavaJava3.0
3GOGO4.0
4NaNNaN5.0
5SQLSQL6.0
6PHPPHP7.0

20.统计grammer列每个字符串的长度

df = pd.DataFrame(data)
df['grammer'] = df['grammer'].fillna('R')
df
grammerscore
0Python1.0
1C2.0
2JavaNaN
3GO4.0
4R5.0
5SQL6.0
6PHP7.0
7Python10.0
df['len_str'] = df['grammer'].map(lambda x: len(x))
df
grammerscorelen_str
0Python1.06
1C2.01
2JavaNaN4
3GO4.02
4R5.01
5SQL6.03
6PHP7.03
7Python10.06

第二期

23 将salary列数据转换为最大值与最小值的平均值

df = pd.read_excel("./pandas1206855/pandas120.xlsx")
df.tail()
createTimeeducationsalary
1302020-03-16 11:36:07本科10k-18k
1312020-03-16 09:54:47硕士25k-50k
1322020-03-16 10:48:32本科20k-40k
1332020-03-16 10:46:31本科15k-23k
1342020-03-16 11:19:38本科20k-40k
import re

方法1

lst = df['salary'].values
lst[:5]
array(['20k-35k', '20k-40k', '20k-35k', '13k-20k', '10k-20k'],
      dtype=object)
b = lst[0]
b = str(b)
b
'20k-35k'
qq = b.split("-")
qq[0],qq[1]
('20k', '35k')
qqq = qq[0].strip("k")
int(qqq)
20
arr变为list
list_1 = [i for i in lst]
用“-”分割
qa = [i.split("-") for i in list_1]
1个列表中嵌套列表,用推导式分开
list_min = [i[0] for i in qa]
list_max = [i[1] for i in qa]
list_min[:5],list_max[:5]
(['20k', '20k', '20k', '13k', '10k'], ['35k', '40k', '35k', '20k', '20k'])
去掉列表中的k
list_min_1 = [i.strip("k") for i in list_min]
list_max_1 = [i.strip("k") for i in list_max]
list_min_1[:5],list_max_1[:5]
(['20', '20', '20', '13', '10'], ['35', '40', '35', '20', '20'])
字符串化为整型
arr_min_2 = np.array(list_min_1,dtype=np.int32)
arr_max_2 = np.array(list_max_1,dtype=np.int32)
arr_min_2[:5],arr_max_2[:5]
(array([20, 20, 20, 13, 10]), array([35, 40, 35, 20, 20]))
求取平均值
salary_1 = (arr_max_2+arr_min_2)/2*1000
df["salary"] = salary_1
df.tail()
createTimeeducationsalary
1302020-03-16 11:36:07本科14000.0
1312020-03-16 09:54:47硕士37500.0
1322020-03-16 10:48:32本科30000.0
1332020-03-16 10:46:31本科19000.0
1342020-03-16 11:19:38本科30000.0

方法3:

df = pd.read_excel("./pandas1206855/pandas120.xlsx")
for index,row in df.iterrows():
    nums = re.findall('\d+',row[2])
    df.iloc[index,2] = int(eval(f'({nums[0]} + {nums[1]}) / 2 * 1000'))
df.tail()
createTimeeducationsalary
1302020-03-16 11:36:07本科14000
1312020-03-16 09:54:47硕士37500
1322020-03-16 10:48:32本科30000
1332020-03-16 10:46:31本科19000
1342020-03-16 11:19:38本科30000

方法2

df = pd.read_excel("./pandas1206855/pandas120.xlsx")
def func(df):
    lst = df['salary'].split('-')
    smin = int(lst[0].strip('k'))
    smax = int(lst[1].strip('k'))
    df['salary'] = int((smin + smax) / 2 * 1000)
    return df

df = df.apply(func,axis=1)
df.tail()
createTimeeducationsalary
1302020-03-16 11:36:07本科14000
1312020-03-16 09:54:47硕士37500
1322020-03-16 10:48:32本科30000
1332020-03-16 10:46:31本科19000
1342020-03-16 11:19:38本科30000

24.将数据根据学历进行分组并计算平均薪资

df.groupby("education").mean()
salary
education
不限19600.000000
大专10000.000000
本科19361.344538
硕士20642.857143

25.将createTime列时间转换为月-日

for i in range(len(df)):
    df.iloc[i,0] = df.iloc[i,0].to_pydatetime().strftime("%m-%d")  
df.head()
createTimeeducationsalary
003-16本科27500
103-16本科30000
203-16不限27500
303-16本科16500
403-16本科15000

27.查看数值型列的汇总统计

df.describe()
salary
count135.000000
mean19159.259259
std8661.686922
min3500.000000
25%14000.000000
50%17500.000000
75%25000.000000
max45000.000000

28 新增一列根据salary将数据分为三组

bins = [0,10000, 20000, 50000]
group_names = ['低', '中', '高']
df['categories'] = pd.cut(df['salary'], bins, labels=group_names)
df
createTimeeducationsalarycategories
003-16本科27500
103-16本科30000
203-16不限27500
303-16本科16500
403-16本科15000
...............
13003-16本科14000
13103-16硕士37500
13203-16本科30000
13303-16本科19000
13403-16本科30000

135 rows × 4 columns

29.按照salary列对数据降序排列

df.sort_values('salary', ascending=False) # ascending:升  descend 下降
createTimeeducationsalarycategories
5303-16本科45000
3703-16本科40000
10103-16本科37500
1603-16本科37500
13103-16硕士37500
...............
12303-16本科4500
12603-16本科4000
11003-16本科4000
9603-16不限3500
11303-16本科3500

135 rows × 4 columns

30.取出第30行

df.iloc[32]
createTime    03-16
education        硕士
salary        22500
categories        高
Name: 32, dtype: object

31 计算salary列的中位数

np.median(df["salary"])
17500.0

32.绘制薪资水平频率分布直方图

df.salary.plot(kind='hist')
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mC61mIJO-1606139752537)(output_117_0.png)]

33.绘制薪资水平密度曲线

df.salary.plot(kind='kde',xlim=(0,80000))
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mZjj1pqp-1606139752538)(output_119_0.png)]

34.删除最后一列categories

axis:使用0值表示沿着每一列或行标签\索引值向下执行方法,使用1值表示沿着每一行或者列标签模向执行对应的方法
df.drop(columns=["categories"])
createTimeeducationsalary
003-16本科27500
103-16本科30000
203-16不限27500
303-16本科16500
403-16本科15000
............
13003-16本科14000
13103-16硕士37500
13203-16本科30000
13303-16本科19000
13403-16本科30000

135 rows × 3 columns

df.drop(labels=“categories”,axis=1)

35.将df的第一列与第二列合并为新的一列

df["test"] = df["education"]+df["createTime"]
df.tail()
createTimeeducationsalarycategoriestest
13003-16本科14000本科03-16
13103-16硕士37500硕士03-16
13203-16本科30000本科03-16
13303-16本科19000本科03-16
13403-16本科30000本科03-16
df.columns
Index(['createTime', 'education', 'salary', 'categories', 'test'], dtype='object')

df.columns[[]]
Index([], dtype='object')
df.columns[[4,0,1,2,3]]
Index(['test', 'createTime', 'education', 'salary', 'categories'], dtype='object')
df[df.columns[[4,0,1,2,3]]].tail()
testcreateTimeeducationsalarycategories
130本科03-1603-16本科14000
131硕士03-1603-16硕士37500
132本科03-1603-16本科30000
133本科03-1603-16本科19000
134本科03-1603-16本科30000

36.将education列与salary列合并为新的一列

df["test_1"] = str(df["salary"])+df["education"]
df.tail()
createTimeeducationsalarycategoriestesttest_1
13003-16本科14000本科03-160 27500\n1 30000\n2 27500\n3 ...
13103-16硕士37500硕士03-160 27500\n1 30000\n2 27500\n3 ...
13203-16本科30000本科03-160 27500\n1 30000\n2 27500\n3 ...
13303-16本科19000本科03-160 27500\n1 30000\n2 27500\n3 ...
13403-16本科30000本科03-160 27500\n1 30000\n2 27500\n3 ...
df["test_1"] = df["salary"].map(str)+df["education"]
df.tail()
createTimeeducationsalarycategoriestesttest_1
13003-16本科14000本科03-1614000本科
13103-16硕士37500硕士03-1637500硕士
13203-16本科30000本科03-1630000本科
13303-16本科19000本科03-1619000本科
13403-16本科30000本科03-1630000本科

37.计算salary最大值与最小值之差

df[‘name’]#得到的是不包含列索引的Series结构
df[[‘name’]]#得到是包含列索引的DataFrame结构
df.name#得到是不包含列索引的Series结构

df[["salary"]].tail()
salary
13014000
13137500
13230000
13319000
13430000
df["salary"].tail()
130    14000
131    37500
132    30000
133    19000
134    30000
Name: salary, dtype: int64
df.salary.tail()
130    14000
131    37500
132    30000
133    19000
134    30000
Name: salary, dtype: int64
df[["salary"]].apply(lambda x : x.max()-x.min())
salary    41500
dtype: int64

38.将第一行与最后一行拼接

pd.concat([df[:1],df[-2:-1]])
createTimeeducationsalarycategoriestesttest_1
003-16本科27500本科03-1627500本科
13303-16本科19000本科03-1619000本科

39.将第8行数据添加至末尾

df[8:9]
createTimeeducationsalarycategoriestesttest_1
803-16不限7000不限03-167000不限
df.iloc[8,:]
createTime      03-16
education          不限
salary           7000
categories          低
test          不限03-16
test_1         7000不限
Name: 8, dtype: object
df.iloc[:,[2,4]]
salarytest
027500本科03-16
130000本科03-16
227500不限03-16
316500本科03-16
415000本科03-16
.........
13014000本科03-16
13137500硕士03-16
13230000本科03-16
13319000本科03-16
13430000本科03-16

135 rows × 2 columns

df.iloc[[2,4],:]
createTimeeducationsalarycategoriestesttest_1
203-16不限27500不限03-1627500不限
403-16本科15000本科03-1615000本科
df.iloc[[8]]
createTimeeducationsalarycategoriestesttest_1
803-16不限7000不限03-167000不限
df.append(df[8:9])
createTimeeducationsalarycategoriestesttest_1
003-16本科27500本科03-1627500本科
103-16本科30000本科03-1630000本科
203-16不限27500不限03-1627500不限
303-16本科16500本科03-1616500本科
403-16本科15000本科03-1615000本科
.....................
13103-16硕士37500硕士03-1637500硕士
13203-16本科30000本科03-1630000本科
13303-16本科19000本科03-1619000本科
13403-16本科30000本科03-1630000本科
803-16不限7000不限03-167000不限

136 rows × 6 columns

41.将createTime列设置为索引

df.set_index("createTime")
educationsalarycategoriestesttest_1
createTime
03-16本科27500本科03-1627500本科
03-16本科30000本科03-1630000本科
03-16不限27500不限03-1627500不限
03-16本科16500本科03-1616500本科
03-16本科15000本科03-1615000本科
..................
03-16本科14000本科03-1614000本科
03-16硕士37500硕士03-1637500硕士
03-16本科30000本科03-1630000本科
03-16本科19000本科03-1619000本科
03-16本科30000本科03-1630000本科

135 rows × 5 columns

42.生成一个和df长度相同的随机数dataframe

df1 = pd.DataFrame(pd.Series(np.random.randint(1, 10, 135)))
df1
0
05
11
22
39
43
......
1302
1319
1329
1334
1347

135 rows × 1 columns

43.将上一题生成的dataframe与df合并

df= pd.concat([df,df1],axis=1)
df
createTimeeducationsalarycategoriestesttest_10
003-16本科27500本科03-1627500本科5
103-16本科30000本科03-1630000本科1
203-16不限27500不限03-1627500不限2
303-16本科16500本科03-1616500本科9
403-16本科15000本科03-1615000本科3
........................
13003-16本科14000本科03-1614000本科2
13103-16硕士37500硕士03-1637500硕士9
13203-16本科30000本科03-1630000本科9
13303-16本科19000本科03-1619000本科4
13403-16本科30000本科03-1630000本科7

135 rows × 7 columns

44.生成新的一列new为salary列减去之前生成随机数列

df["new"] = df["salary"] - df[0]
df
createTimeeducationsalarycategoriestesttest_10new
003-16本科27500本科03-1627500本科527495
103-16本科30000本科03-1630000本科129999
203-16不限27500不限03-1627500不限227498
303-16本科16500本科03-1616500本科916491
403-16本科15000本科03-1615000本科314997
...........................
13003-16本科14000本科03-1614000本科213998
13103-16硕士37500硕士03-1637500硕士937491
13203-16本科30000本科03-1630000本科929991
13303-16本科19000本科03-1619000本科418996
13403-16本科30000本科03-1630000本科729993

135 rows × 8 columns

45.检查数据中是否含有任何缺失值

df.isnull().values.any()
False

46.将salary列类型转换为浮点数

df['salary'].astype(np.float64)
0      27500.0
1      30000.0
2      27500.0
3      16500.0
4      15000.0
        ...   
130    14000.0
131    37500.0
132    30000.0
133    19000.0
134    30000.0
Name: salary, Length: 135, dtype: float64

47.计算salary大于10000的次数

len(df[df['salary']>8000])
123

48.查看每种学历出现的次数

df.education.value_counts()
本科    119
硕士      7
不限      5
大专      4
Name: education, dtype: int64
df["education"].value_counts()
本科    119
硕士      7
不限      5
大专      4
Name: education, dtype: int64
df[["education"]].value_counts()
education
本科           119
硕士             7
不限             5
大专             4
dtype: int64

49.查看education列共有几种学历

df["education"].unique()
array(['本科', '不限', '硕士', '大专'], dtype=object)
df["education"].nunique()
4

50.提取salary与new列的和大于60000的最后3行

df1 = df[['salary','new']]
rowsums = df1.apply(np.sum, axis=1)
res = df.iloc[np.where(rowsums > 60000)[0][-3:], :]
res
createTimeeducationsalarycategoriestesttest_10new
9203-16本科35000本科03-1635000本科534995
10103-16本科37500本科03-1637500本科337497
13103-16硕士37500硕士03-1637500硕士937491
df1.tail()
salarynew
1301400013998
1313750037491
1323000029991
1331900018996
1343000029993
rowsums
0      54995
1      59999
2      54998
3      32991
4      29997
       ...  
130    27998
131    74991
132    59991
133    37996
134    59993
Length: 135, dtype: int64

51.使用绝对路径读取本地Excel数据

url_one = r'D:\exercise\pandas1206855\600000.SH.xls'
df = pd.read_excel(url_one)
WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero
df.head(3)
代码简称日期前收盘价(元)开盘价(元)最高价(元)最低价(元)收盘价(元)成交量(股)成交金额(元)涨跌(元)涨跌幅(%)均价(元)换手率(%)A股流通市值(元)总市值(元)A股流通股本(股)市盈率
0600000.SH浦发银行2016-01-0416.135616.144416.144415.499715.720542240610754425783-0.4151-2.572517.86020.22643.320318e+113.320318e+111.865347e+106.5614
1600000.SH浦发银行2016-01-0515.720515.464415.950115.367215.86185805479310341814740.14130.898917.81390.31123.350163e+113.350163e+111.865347e+106.6204
2600000.SH浦发银行2016-01-0615.861815.808816.020815.623415.9855467726538386673980.12360.779517.93070.25073.376278e+113.376278e+111.865347e+106.6720

53.查看每列数据缺失值情况

df.isnull().sum()
代码           1
简称           2
日期           2
前收盘价(元)      2
开盘价(元)       2
最高价(元)       2
最低价(元)       2
收盘价(元)       2
成交量(股)       2
成交金额(元)      2
涨跌(元)        2
涨跌幅(%)       2
均价(元)        2
换手率(%)       2
A股流通市值(元)    2
总市值(元)       2
A股流通股本(股)    2
市盈率          2
dtype: int64

54.提取日期列含有空值的行

df[df["日期"].isnull()]
代码简称日期前收盘价(元)开盘价(元)最高价(元)最低价(元)收盘价(元)成交量(股)成交金额(元)涨跌(元)涨跌幅(%)均价(元)换手率(%)A股流通市值(元)总市值(元)A股流通股本(股)市盈率
327NaNNaNNaTNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
328数据来源:Wind资讯NaNNaTNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN

55.输出每列缺失值具体行数

for columname in df.columns:
    if df[columname].count() != len(data):
        loc = df[columname][df[columname].isnull().values==True].index.tolist()
        print('列名:"{}", 第{}行位置有缺失值'.format(columname,loc))
列名:"代码", 第[327]行位置有缺失值
列名:"简称", 第[327, 328]行位置有缺失值
列名:"日期", 第[327, 328]行位置有缺失值
列名:"前收盘价(元)", 第[327, 328]行位置有缺失值
列名:"开盘价(元)", 第[327, 328]行位置有缺失值
列名:"最高价(元)", 第[327, 328]行位置有缺失值
列名:"最低价(元)", 第[327, 328]行位置有缺失值
列名:"收盘价(元)", 第[327, 328]行位置有缺失值
列名:"成交量(股)", 第[327, 328]行位置有缺失值
列名:"成交金额(元)", 第[327, 328]行位置有缺失值
列名:"涨跌(元)", 第[327, 328]行位置有缺失值
列名:"涨跌幅(%)", 第[327, 328]行位置有缺失值
列名:"均价(元)", 第[327, 328]行位置有缺失值
列名:"换手率(%)", 第[327, 328]行位置有缺失值
列名:"A股流通市值(元)", 第[327, 328]行位置有缺失值
列名:"总市值(元)", 第[327, 328]行位置有缺失值
列名:"A股流通股本(股)", 第[327, 328]行位置有缺失值
列名:"市盈率", 第[327, 328]行位置有缺失值

56.删除所有存在缺失值的行

'''
备注
axis:0-行操作(默认),1-列操作
how:any-只要有空值就删除(默认),all-全部为空值才删除
inplace:False-返回新的数据集(默认),True-在原数据集上操作
'''
data = df
df.dropna(axis=0, how='any', inplace=True)
df.tail()
代码简称日期前收盘价(元)开盘价(元)最高价(元)最低价(元)收盘价(元)成交量(股)成交金额(元)涨跌(元)涨跌幅(%)均价(元)换手率(%)A股流通市值(元)总市值(元)A股流通股本(股)市盈率
322600000.SH浦发银行2017-05-0315.1615.1615.1615.0515.0814247943215130847-0.08-0.527715.09910.06593.260037e+113.260037e+112.161828e+106.1395
323600000.SH浦发银行2017-05-0415.0815.0715.0714.9014.9819477788291839737-0.10-0.663114.98320.09013.238418e+113.238418e+112.161828e+106.0988
324600000.SH浦发银行2017-05-0514.9814.9514.9814.5214.9240194577592160198-0.06-0.400514.73230.18593.225447e+113.225447e+112.161828e+106.0744
325600000.SH浦发银行2017-05-0814.9214.7814.9014.5114.8643568576638781010-0.06-0.402114.66150.20153.212476e+113.212476e+112.161828e+106.0500
326600000.SH浦发银行2017-05-0914.8614.6914.8414.6614.7619225492283864640-0.10-0.672914.7650.08893.190858e+113.190858e+112.161828e+106.0093

57.绘制收盘价的折线图

import matplotlib.pyplot as plt 
plt.style.use('seaborn-darkgrid') # 设置画图的风格
plt.rc('font',  size=6) #设置图中字体和大小
plt.rc('figure', figsize=(4,3), dpi=150) # 设置图的大小
df["收盘价(元)"].plot()
<AxesSubplot:>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BY6RLYWY-1606139752541)(output_189_1.png)]

# 等价于
import matplotlib.pyplot as plt
plt.plot(df['收盘价(元)'])
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GTSU9MFt-1606139752543)(output_190_0.png)]

58.同时绘制开盘价与收盘价

df[['收盘价(元)','开盘价(元)']].plot()
<AxesSubplot:>



E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 25910 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 30424 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 20215 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 20803 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 24320 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 25910 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 30424 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 20215 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 20803 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 24320 missing from current font.
  font.set_text(s, 0, flags=flags)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1oGzXF0M-1606139752544)(output_192_2.png)]

59.绘制涨跌幅的直方图

plt.hist(df['涨跌幅(%)'])
# 等价于
df['涨跌幅(%)'].hist()
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-99LGRTuT-1606139752545)(output_194_0.png)]

data = df
data['涨跌幅(%)'].hist(bins = 30) ##更细致
<AxesSubplot:>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xvW5p9k0-1606139752546)(output_195_1.png)]

60.让直方图更细致

data['涨跌幅(%)'].hist(bins = 30)
<AxesSubplot:>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9TaQG7nW-1606139752547)(output_197_1.png)]

61.以data的列名创建一个dataframe

temp = pd.DataFrame(columns = data.columns.to_list())
data.columns
Index(['代码', '简称', '日期', '前收盘价(元)', '开盘价(元)', '最高价(元)', '最低价(元)', '收盘价(元)',
       '成交量(股)', '成交金额(元)', '涨跌(元)', '涨跌幅(%)', '均价(元)', '换手率(%)', 'A股流通市值(元)',
       '总市值(元)', 'A股流通股本(股)', '市盈率'],
      dtype='object')
data.columns.to_list()
['代码',
 '简称',
 '日期',
 '前收盘价(元)',
 '开盘价(元)',
 '最高价(元)',
 '最低价(元)',
 '收盘价(元)',
 '成交量(股)',
 '成交金额(元)',
 '涨跌(元)',
 '涨跌幅(%)',
 '均价(元)',
 '换手率(%)',
 'A股流通市值(元)',
 '总市值(元)',
 'A股流通股本(股)',
 '市盈率']

62.打印所有换手率不是数字的行

for i in range(len(data)):
    if type(data.iloc[i,13]) != float:
        temp = temp.append(data.loc[i])

temp
代码简称日期前收盘价(元)开盘价(元)最高价(元)最低价(元)收盘价(元)成交量(股)成交金额(元)涨跌(元)涨跌幅(%)均价(元)换手率(%)A股流通市值(元)总市值(元)A股流通股本(股)市盈率
26600000.SH浦发银行2016-02-1616.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
27600000.SH浦发银行2016-02-1716.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
28600000.SH浦发银行2016-02-1816.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
29600000.SH浦发银行2016-02-1916.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
30600000.SH浦发银行2016-02-2216.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
31600000.SH浦发银行2016-02-2316.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
32600000.SH浦发银行2016-02-2416.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
33600000.SH浦发银行2016-02-2516.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
34600000.SH浦发银行2016-02-2616.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
35600000.SH浦发银行2016-02-2916.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
36600000.SH浦发银行2016-03-0116.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
37600000.SH浦发银行2016-03-0216.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
38600000.SH浦发银行2016-03-0316.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
39600000.SH浦发银行2016-03-0416.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
40600000.SH浦发银行2016-03-0716.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
41600000.SH浦发银行2016-03-0816.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
42600000.SH浦发银行2016-03-0916.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
43600000.SH浦发银行2016-03-1016.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801

63.打印所有换手率为–的行

data[data['换手率(%)'].isin(['--'])]
代码简称日期前收盘价(元)开盘价(元)最高价(元)最低价(元)收盘价(元)成交量(股)成交金额(元)涨跌(元)涨跌幅(%)均价(元)换手率(%)A股流通市值(元)总市值(元)A股流通股本(股)市盈率
26600000.SH浦发银行2016-02-1616.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
27600000.SH浦发银行2016-02-1716.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
28600000.SH浦发银行2016-02-1816.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
29600000.SH浦发银行2016-02-1916.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
30600000.SH浦发银行2016-02-2216.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
31600000.SH浦发银行2016-02-2316.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
32600000.SH浦发银行2016-02-2416.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
33600000.SH浦发银行2016-02-2516.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
34600000.SH浦发银行2016-02-2616.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
35600000.SH浦发银行2016-02-2916.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
36600000.SH浦发银行2016-03-0116.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
37600000.SH浦发银行2016-03-0216.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
38600000.SH浦发银行2016-03-0316.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
39600000.SH浦发银行2016-03-0416.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
40600000.SH浦发银行2016-03-0716.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
41600000.SH浦发银行2016-03-0816.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
42600000.SH浦发银行2016-03-0916.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801
43600000.SH浦发银行2016-03-1016.294616.294616.294616.294616.2946----0.00.0----3.441565e+113.441565e+111.865347e+106.801

64.重置data的行号

data = data.reset_index()

65.删除所有换手率为非数字的行

k =[]
for i in range(len(data)):
    if type(data.iloc[i,13]) != float:
        k.append(i)
data.drop(labels=k,inplace=True)

66.绘制换手率的密度曲线

data['换手率(%)'].plot(kind='kde')
<AxesSubplot:ylabel='Density'>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jL73dTog-1606139752549)(output_211_1.png)]

67.计算前一天与后一天收盘价的差值

data['收盘价(元)'].diff()
0         NaN
1      0.1413
2      0.1237
3     -0.5211
4     -0.0177
        ...  
322   -0.0800
323   -0.1000
324   -0.0600
325   -0.0600
326   -0.1000
Name: 收盘价(元), Length: 309, dtype: float64

68.计算前一天与后一天收盘价变化率

data['收盘价(元)'].pct_change()
0           NaN
1      0.008988
2      0.007799
3     -0.032598
4     -0.001145
         ...   
322   -0.005277
323   -0.006631
324   -0.004005
325   -0.004021
326   -0.006729
Name: 收盘价(元), Length: 309, dtype: float64

69.设置日期为索引

data = data.set_index('日期')
data.tail()
index代码简称前收盘价(元)开盘价(元)最高价(元)最低价(元)收盘价(元)成交量(股)成交金额(元)涨跌(元)涨跌幅(%)均价(元)换手率(%)A股流通市值(元)总市值(元)A股流通股本(股)市盈率
日期
2017-05-03322600000.SH浦发银行15.1615.1615.1615.0515.0814247943215130847-0.08-0.527715.09910.06593.260037e+113.260037e+112.161828e+106.1395
2017-05-04323600000.SH浦发银行15.0815.0715.0714.9014.9819477788291839737-0.10-0.663114.98320.09013.238418e+113.238418e+112.161828e+106.0988
2017-05-05324600000.SH浦发银行14.9814.9514.9814.5214.9240194577592160198-0.06-0.400514.73230.18593.225447e+113.225447e+112.161828e+106.0744
2017-05-08325600000.SH浦发银行14.9214.7814.9014.5114.8643568576638781010-0.06-0.402114.66150.20153.212476e+113.212476e+112.161828e+106.0500
2017-05-09326600000.SH浦发银行14.8614.6914.8414.6614.7619225492283864640-0.10-0.672914.7650.08893.190858e+113.190858e+112.161828e+106.0093

70.以5个数据作为一个数据滑动窗口,在这个5个数据上取均值(收盘价)

data['收盘价(元)'].rolling(5).mean()

日期
2016-01-04         NaN
2016-01-05         NaN
2016-01-06         NaN
2016-01-07         NaN
2016-01-08    15.69578
                ...   
2017-05-03    15.14200
2017-05-04    15.12800
2017-05-05    15.07000
2017-05-08    15.00000
2017-05-09    14.92000
Name: 收盘价(元), Length: 309, dtype: float64

71.以5个数据作为一个数据滑动窗口,计算这五个数据总和(收盘价)

data['收盘价(元)'].rolling(5).sum()

日期
2016-01-04        NaN
2016-01-05        NaN
2016-01-06        NaN
2016-01-07        NaN
2016-01-08    78.4789
               ...   
2017-05-03    75.7100
2017-05-04    75.6400
2017-05-05    75.3500
2017-05-08    75.0000
2017-05-09    74.6000
Name: 收盘价(元), Length: 309, dtype: float64

72.将收盘价5日均线、20日均线与原始数据绘制在同一个图上

data['收盘价(元)'].plot()
data['收盘价(元)'].rolling(5).mean().plot()
data['收盘价(元)'].rolling(20).mean().plot()
plt.show()
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26085 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26399 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 26085 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 26399 missing from current font.
  font.set_text(s, 0, flags=flags)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9fkJ9O1H-1606139752550)(output_224_1.png)]

73.按周为采样规则,取一周收盘价最大值

data['收盘价(元)'].resample('W').max()
日期
2016-01-10    15.9855
2016-01-17    15.8265
2016-01-24    15.6940
2016-01-31    15.0405
2016-02-07    16.2328
               ...   
2017-04-16    15.9700
2017-04-23    15.5600
2017-04-30    15.2100
2017-05-07    15.1600
2017-05-14    14.8600
Freq: W-SUN, Name: 收盘价(元), Length: 71, dtype: float64

74.绘制重采样数据与原始数据

data['收盘价(元)'].plot()
data['收盘价(元)'].resample('7D').max().plot()
<AxesSubplot:xlabel='日期'>



E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26085 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26399 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 26085 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 26399 missing from current font.
  font.set_text(s, 0, flags=flags)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r26wfrk2-1606139752551)(output_228_2.png)]

75.将数据往后移动5天

data.shift(5)

index代码简称前收盘价(元)开盘价(元)最高价(元)最低价(元)收盘价(元)成交量(股)成交金额(元)涨跌(元)涨跌幅(%)均价(元)换手率(%)A股流通市值(元)总市值(元)A股流通股本(股)市盈率
日期
2016-01-04NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2016-01-05NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2016-01-06NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2016-01-07NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2016-01-08NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
.........................................................
2017-05-03317.0600000.SH浦发银行15.0015.0215.1014.9915.05129759191952968620.050.333315.05070.063.253551e+113.253551e+112.161828e+106.1273
2017-05-04318.0600000.SH浦发银行15.0515.0615.1115.0015.05149398712250226680.000.000015.06190.06913.253551e+113.253551e+112.161828e+106.1273
2017-05-05319.0600000.SH浦发银行15.0515.0515.2515.0315.21228876453457915260.161.063115.10820.10593.288140e+113.288140e+112.161828e+106.1925
2017-05-08320.0600000.SH浦发银行15.2115.1515.2215.0815.21157185092384191610.000.000015.16810.07273.288140e+113.288140e+112.161828e+106.1925
2017-05-09321.0600000.SH浦发银行15.2115.2115.2215.1315.1612607509191225527-0.05-0.328715.16760.05833.277331e+113.277331e+112.161828e+106.1721

309 rows × 18 columns

76.将数据向前移动5天

data.shift(-5)

index代码简称前收盘价(元)开盘价(元)最高价(元)最低价(元)收盘价(元)成交量(股)成交金额(元)涨跌(元)涨跌幅(%)均价(元)换手率(%)A股流通市值(元)总市值(元)A股流通股本(股)市盈率
日期
2016-01-045.0600000.SH浦发银行15.446715.199415.411414.978615.0581901771351550155933-0.3886-2.515717.19010.48343.180417e+113.180417e+111.865347e+106.2849
2016-01-056.0600000.SH浦发银行15.058115.164115.473215.084615.4114553744549640615020.35332.346017.40990.29693.255031e+113.255031e+111.865347e+106.4324
2016-01-067.0600000.SH浦发银行15.411415.517415.808815.323115.358447869312843717365-0.0530-0.343817.62540.25663.243839e+113.243839e+111.865347e+106.4102
2016-01-078.0600000.SH浦发银行15.358415.014015.888314.916815.8265548388339661178480.46813.047717.61740.2943.342702e+113.342702e+111.865347e+106.6056
2016-01-089.0600000.SH浦发银行15.826515.720516.029615.473215.526246723139836146426-0.3003-1.897317.89580.25053.279280e+113.279280e+111.865347e+106.4803
.........................................................
2017-05-03NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2017-05-04NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2017-05-05NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2017-05-08NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2017-05-09NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN

309 rows × 18 columns

77.使用expending函数计算开盘价的移动窗口均值

data['开盘价(元)'].expanding(min_periods=1).mean()
日期
2016-01-04    16.144400
2016-01-05    15.804400
2016-01-06    15.805867
2016-01-07    15.784525
2016-01-08    15.761120
                ...    
2017-05-03    16.041489
2017-05-04    16.038314
2017-05-05    16.034769
2017-05-08    16.030695
2017-05-09    16.026356
Name: 开盘价(元), Length: 309, dtype: float64

78.绘制上一题的移动均值与原始数据折线图

data['expanding Open mean']=data['开盘价(元)'].expanding(min_periods=1).mean()
data[['开盘价(元)', 'expanding Open mean']].plot(figsize=(16, 6))
<AxesSubplot:xlabel='日期'>



E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26085 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26399 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 24320 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 30424 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 20215 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 20803 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 26085 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 26399 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 24320 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 30424 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 20215 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 20803 missing from current font.
  font.set_text(s, 0, flags=flags)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Y3WeqcaC-1606139752552)(output_236_2.png)]

79.计算布林指标

data['former 30 days rolling Close mean']=data['收盘价(元)'].rolling(20).mean()
data['upper bound']=data['former 30 days rolling Close mean']+2*data['收盘价(元)'].rolling(20).std()#在这里我们取20天内的标准差
data['lower bound']=data['former 30 days rolling Close mean']-2*data['收盘价(元)'].rolling(20).std()

80.计算布林线并绘制

data[['收盘价(元)', 'former 30 days rolling Close mean','upper bound','lower bound' ]].plot(figsize=(16, 6))
<AxesSubplot:xlabel='日期'>



E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26085 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26399 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 25910 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 30424 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 20215 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 20803 missing from current font.
  font.set_text(s, 0.0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 26085 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 26399 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 25910 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 30424 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 20215 missing from current font.
  font.set_text(s, 0, flags=flags)
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 20803 missing from current font.
  font.set_text(s, 0, flags=flags)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aGno7OXK-1606139752553)(output_240_2.png)]

81.导入并查看pandas与numpy版本

import pandas as pd
import numpy as np
print(np.__version__)
print(pd.__version__)
1.19.1
1.1.1

82.从NumPy数组创建DataFrame

#备注 使用numpy生成20个0-100随机数
tem = np.random.randint(1,100,20)
df1 = pd.DataFrame(tem)
df1.tail()
0
1536
1662
1763
1810
1933
#备注 使用numpy生成20个0-100固定步长的数
tem = np.arange(0,100,5)
df2 = pd.DataFrame(tem)
df2.tail()
0
1575
1680
1785
1890
1995

84.从NumPy数组创建DataFrame

#备注 使用numpy生成20个指定分布(如标准正态分布)的数
tem = np.random.normal(0, 1, 20)
df3 = pd.DataFrame(tem)
df3.tail()
0
15-0.379478
161.326701
170.670421
18-0.291537
190.817611

85.将df1,df2,df3按照行合并为新DataFrame

df = pd.concat([df1,df2,df3],axis=0,ignore_index=True)
df.tail()
0
55-0.379478
561.326701
570.670421
58-0.291537
590.817611
df = pd.concat([df1,df2,df3],axis=1,ignore_index=True)
df.tail()
012
153675-0.379478
1662801.326701
1763850.670421
181090-0.291537
1933950.817611

87.查看df所有数据的最小值、25%分位数、中位数、75%分位数、最大值

print(np.percentile(df, q=[0, 25, 50, 75, 100]))
[-1.80791481  0.6438385  12.5        56.25       95.        ]

88.修改列名为col1,col2,col3

df.columns = ['col1','col2','col3']
df.tail()
col1col2col3
153675-0.379478
1662801.326701
1763850.670421
181090-0.291537
1933950.817611

89.提取第一列中不在第二列出现的数字

df['col1'][~df['col1'].isin(df['col2'])] # 不在:是在前面加一个~
0      2
1      7
2     74
3     67
4     72
5      8
6     29
7     87
8      4
10    91
11    43
13     3
14     7
15    36
16    62
17    63
19    33
Name: col1, dtype: int32

90.提取第一列和第二列出现频率最高的三个数字

temp = df['col1'].append(df['col2'])
temp.value_counts().index[:3]
Int64Index([25, 10, 7], dtype='int64')
temp.value_counts().head(10)
25    3
10    2
7     2
2     1
67    1
4     1
65    1
5     1
70    1
87    1
dtype: int64

92.计算第一列数字前一个与后一个的差值

df['col1'].diff().tolist()
[nan,
 5.0,
 67.0,
 -7.0,
 5.0,
 -64.0,
 21.0,
 58.0,
 -83.0,
 21.0,
 66.0,
 -48.0,
 -18.0,
 -22.0,
 4.0,
 29.0,
 26.0,
 1.0,
 -53.0,
 23.0]

93.将col1,col2,clo3三列顺序颠倒

b = a[i:j] 表示复制a[i]到a[j-1],以生成新的list对象

a = [0,1,2,3,4,5,6,7,8,9]
b = a[1:3] # [1,2]
当i缺省时,默认为0,即 a[:3]相当于 a[0:3]
当j缺省时,默认为len(alist), 即a[1:]相当于a[1:10]
当i,j都缺省时,a[:]就相当于完整复制一份a

b = a[i:j:s]表示:i,j与上面的一样,但s表示步进,缺省为1.
所以a[i:j:1]相当于a[i:j]
当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1
所以a[::-1]相当于 a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍,即倒序。

df.iloc[:, ::-1]
col3col2col1
0-1.04961002
10.12053657
2-0.4721641074
31.2085511567
4-1.8079152072
5-0.608977258
60.5640923029
7-0.2084673587
8-0.645818404
90.9735544525
10-0.0647075091
110.1481135543
12-0.2508236025
13-0.334750653
141.626963707
15-0.3794787536
161.3267018062
170.6704218563
18-0.2915379010
190.8176119533

94.提取第一列位置在1,10,15的数字

df['col1'].take([1,10,15])
1      7
10    91
15    36
Name: col1, dtype: int32
# 等价于
df.iloc[[1,10,15],0]
1      7
10    91
15    36
Name: col1, dtype: int32

95.查找第一列的局部最大值位置

tem = np.diff(np.sign(np.diff(df['col1'])))
np.where(tem == -2)[0] + 1
array([ 2,  4,  7, 10, 17], dtype=int64)

96.按行计算df的每一行均值

df[['col1','col2','col3']].mean(axis=1)
0      0.316797
1      4.040179
2     27.842612
3     27.736184
4     30.064028
5     10.797008
6     19.854697
7     40.597178
8     14.451394
9     23.657851
10    46.978431
11    32.716038
12    28.249726
13    22.555083
14    26.208988
15    36.873507
16    47.775567
17    49.556807
18    33.236154
19    42.939204
dtype: float64

97.对第二列计算移动平均值

np.convolve(df['col2'], np.ones(3)/3, mode='valid')
array([ 5., 10., 15., 20., 25., 30., 35., 40., 45., 50., 55., 60., 65.,
       70., 75., 80., 85., 90.])

98.将数据按照第三列值的大小升序排列

df.sort_values("col3",inplace=True)
df["col3"]
4    -1.807915
0    -1.049610
8    -0.645818
5    -0.608977
2    -0.472164
15   -0.379478
13   -0.334750
18   -0.291537
12   -0.250823
7    -0.208467
10   -0.064707
1     0.120536
11    0.148113
6     0.564092
17    0.670421
19    0.817611
9     0.973554
3     1.208551
16    1.326701
14    1.626963
Name: col3, dtype: float64

99.将第一列大于50的数字修改为’高’

df.col1[df['col1'] > 50]= '高'
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  """Entry point for launching an IPython kernel.
df['col1']
4      高
0      2
8      4
5      8
2      高
15    36
13     3
18    10
12    25
7      高
10     高
1      7
11    43
6     29
17     高
19    33
9     25
3      高
16     高
14     7
Name: col1, dtype: object
df.col1
4      高
0      2
8      4
5      8
2      高
15    36
13     3
18    10
12    25
7      高
10     高
1      7
11    43
6     29
17     高
19    33
9     25
3      高
16     高
14     7
Name: col1, dtype: object

100.计算第二列与第三列之间的欧式距离

np.linalg.norm(df['col2']-df['col3'])
247.48229970698026

101.从CSV文件中读取指定数据

df = pd.read_csv('数据1.csv',encoding='gbk', usecols=['positionName', 'salary'],nrows = 10)
df
positionNamesalary
0数据分析37500
1数据建模15000
2数据分析3500
3数据分析45000
4数据分析30000
5数据分析50000
6数据分析30000
7数据建模工程师35000
8数据分析专家60000
9数据分析师40000

102.从CSV文件中读取指定数据

df = pd.read_csv('数据2.csv',converters={'薪资水平': lambda x: '高' if float(x) > 10000 else '低'} )
df
学历要求薪资水平
0本科
1硕士
2本科
3本科
4不限
.........
1149硕士
1150本科
1151本科
1152本科
1153本科

1154 rows × 2 columns

103.从上一题数据中,对薪资水平列每隔20行进行一次抽样

df.iloc[::20, :][['薪资水平']]
薪资水平
0
20
40
60
80
100
120
140
160
180
200
220
240
260
280
300
320
340
360
380
400
420
440
460
480
500
520
540
560
580
600
620
640
660
680
700
720
740
760
780
800
820
840
860
880
900
920
940
960
980
1000
1020
1040
1060
1080
1100
1120
1140

104.将数据取消使用科学计数法

df = pd.DataFrame(np.random.random(10)**10, columns=['data'])
df
data
02.353154e-01
15.046102e-10
21.210372e-02
33.320882e-01
45.618341e-03
57.634267e-01
64.067364e-01
72.449082e-11
86.759164e-12
91.013198e-11
df.round(3)
data
00.235
10.000
20.012
30.332
40.006
50.763
60.407
70.000
80.000
90.000

105.将上一题的数据转换为百分数

df.style.format({'data': '{0:.2%}'.format})
            <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row0" class="row_heading level0 row0" >0</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row0_col0" class="data row0 col0" >23.53%</td>
        </tr>
        <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row1" class="row_heading level0 row1" >1</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row1_col0" class="data row1 col0" >0.00%</td>
        </tr>
        <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row2" class="row_heading level0 row2" >2</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row2_col0" class="data row2 col0" >1.21%</td>
        </tr>
        <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row3" class="row_heading level0 row3" >3</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row3_col0" class="data row3 col0" >33.21%</td>
        </tr>
        <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row4" class="row_heading level0 row4" >4</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row4_col0" class="data row4 col0" >0.56%</td>
        </tr>
        <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row5" class="row_heading level0 row5" >5</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row5_col0" class="data row5 col0" >76.34%</td>
        </tr>
        <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row6" class="row_heading level0 row6" >6</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row6_col0" class="data row6 col0" >40.67%</td>
        </tr>
        <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row7" class="row_heading level0 row7" >7</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row7_col0" class="data row7 col0" >0.00%</td>
        </tr>
        <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row8" class="row_heading level0 row8" >8</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row8_col0" class="data row8 col0" >0.00%</td>
        </tr>
        <tr>
                    <th id="T_856a8792_2d8f_11eb_b978_1831bf28bee4level0_row9" class="row_heading level0 row9" >9</th>
                    <td id="T_856a8792_2d8f_11eb_b978_1831bf28bee4row9_col0" class="data row9 col0" >0.00%</td>
        </tr>
</tbody></table>
data

106.查找上一题数据中第3大值的行号

df['data'].argsort()[::-1][7]
3

107.反转df的行

df.iloc[::-1, :]
data
91.013198e-11
86.759164e-12
72.449082e-11
64.067364e-01
57.634267e-01
45.618341e-03
33.320882e-01
21.210372e-02
15.046102e-10
02.353154e-01

108.按照多列对数据进行合并

df1= pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})

df2= pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
pd.merge(df1, df2, on=['key1', 'key2'])

key1key2ABCD
0K0K0A0B0C0D0
1K1K0A2B2C1D1
2K1K0A2B2C2D2

109.按照多列对数据进行合并

pd.merge(df1, df2, how='left', on=['key1', 'key2'])
key1key2ABCD
0K0K0A0B0C0D0
1K0K1A1B1NaNNaN
2K1K0A2B2C1D1
3K1K0A2B2C2D2
4K2K1A3B3NaNNaN

110.再次读取数据1并显示所有的列

df = pd.read_csv('数据1.csv',encoding='gbk')
pd.set_option("display.max.columns", None)
df
positionIdpositionNamecompanyIdcompanyLogocompanySizeindustryFieldfinanceStagecompanyLabelListfirstTypesecondTypethirdTypeskillLablespositionLablesindustryLablescreateTimeformatCreateTimedistrictbusinessZonessalaryworkYearjobNatureeducationpositionAdvantageimStatelastLoginpublisherIdapprovesubwaylinestationnamelinestaionlatitudelongitudehitagsresumeProcessRateresumeProcessDayscorenewScorematchScorematchScoreExplainqueryexplainisSchoolJobadWordpluspcShowappShowdelivergradeDescriptionpromotionScoreExplainisHotHirecountaggregatePositionIdsfamousCompany
06802721数据分析475770i/image2/M01/B7/3E/CgoB5lwPfEaAdn8WAABWQ0Jgl5s...50-150人移动互联网,电商A轮['绩效奖金', '带薪年假', '定期体检', '弹性工作']产品|需求|项目类数据分析数据分析['SQL', '数据库', '数据运营', 'BI']['电商', '社交', 'SQL', '数据库', '数据运营', 'BI']['电商', '社交', 'SQL', '数据库', '数据运营', 'BI']2020/3/16 11:0011:00发布余杭区['仓前']375001-3年全职本科五险一金、弹性工作、带薪年假、年度体检today2020/3/16 11:00120224061NaNNaNNaN30.278421120.005922NaN501233015.101875NaNNaNNaN00NaN000NaNNaN00[]False
15204912数据建模50735image1/M00/00/85/CgYXBlTUXeeAR0IjAABbroUk-dw97...150-500人电商B轮['年终奖金', '做五休二', '六险一金', '子女福利']开发|测试|运维类数据开发建模['算法', '数据架构']['算法', '数据架构'][]2020/3/16 11:0811:08发布滨江区['西兴', '长河']150003-5年全职本科六险一金,定期体检,丰厚年终disabled2020/3/16 11:0854916881NaNNaNNaN30.188041120.201179NaN231176032.559414NaNNaNNaN00NaN000NaNNaN00[]False
26877668数据分析100125image2/M00/0C/57/CgqLKVYcOA2ADcFuAAAE8MukIKA74...2000人以上移动互联网,企业服务上市公司['节日礼物', '年底双薪', '股票期权', '带薪年假']产品|需求|项目类数据分析数据分析['数据库', '数据分析', 'SQL']['数据库', 'SQL'][]2020/3/16 10:3310:33发布江干区['四季青', '钱江新城']35001-3年全职本科五险一金 周末双休 不加班 节日福利today2020/3/16 10:33532258314号线江锦路4号线_城星路;4号线_市民中心;4号线_江锦路30.241521120.212539NaN11480014.972357NaNNaNNaN00NaN000NaNNaN00[]False
36496141数据分析26564i/image2/M01/F7/3F/CgoB5lyGAQGAZeI-AAAdOqXecnw...500-2000人电商D轮及以上['生日趴', '每月腐败基金', '每月补贴', '年度旅游']开发|测试|运维类数据开发数据分析[]['电商']['电商']2020/3/16 10:1010:10发布江干区NaN450003-5年全职本科年终奖等threeDays2020/3/16 10:10981456011号线文泽路1号线_文泽路30.299404120.350304NaN100168012.874153NaNNaNNaN00NaN000NaNNaN00[]True
46467417数据分析29211i/image2/M01/77/B8/CgoB5l1WDyGATNP5AAAlY3h88SY...2000人以上物流丨运输上市公司['技能培训', '免费班车', '专项奖金', '岗位晋升']产品|需求|项目类数据分析数据分析['BI', '数据分析', '数据运营']['BI', '数据运营'][]2020/3/16 09:5609:56发布余杭区['仓前']300003-5年全职大专五险一金disabled2020/3/16 09:5663923941NaNNaNNaN30.282952120.009765NaN20166012.755375NaNNaNNaN00NaN000NaNNaN00[]True
..................................................................................................................................................................
1006884346数据分析师21236i/image/M00/43/F6/CgqKkVeEh76AUVPoAAA2Bj747wU6...500-2000人移动互联网,医疗丨健康C轮['技能培训', '年底双薪', '节日礼物', '绩效奖金']产品|需求|项目类数据分析数据分析['数据库', '商业', '数据分析', 'SQL']['医疗健康', '数据库', '商业', '数据分析', 'SQL']['医疗健康', '数据库', '商业', '数据分析', 'SQL']2020/3/11 16:452020/3/11萧山区NaN250003-5年全职不限大牛老板,开放环境,民生行业,龙头公司threeDays2020/3/16 09:4916651671NaNNaNNaN30.203078120.247069NaN961000.314259NaNNaNNaN00NaN000NaNNaN00[]False
1016849100商业数据分析72076i/image2/M01/92/A4/CgotOV2LPUmAR_8dAAB_DlDMiXA...500-2000人移动互联网,电商C轮['节日礼物', '股票期权', '带薪年假', '年度旅游']市场|商务类市场|营销商业数据分析['市场', '数据分析', '行业分析', '市场分析']['电商', '市场', '数据分析', '行业分析', '市场分析']['电商', '市场', '数据分析', '行业分析', '市场分析']2020/3/14 17:382天前发布余杭区NaN350001-3年全职硕士五险一金、带薪休假threeDays2020/3/14 17:3817324161NaNNaNNaN30.276694119.990918NaN23000.283276NaNNaNNaN00NaN000NaNNaN00[]False
1026803432奔驰·耀出行-BI数据分析专家751158i/image3/M01/64/93/Cgq2xl48z2mAeYRoAAD6Qf_Jeq8...150-500人移动互联网不需要融资[]开发|测试|运维类数据开发数据分析['MySQL', '数据处理', '数据分析']['MySQL', '数据处理', '数据分析'][]2020/3/14 22:392天前发布滨江区['西兴']300003-5年全职本科奔驰 吉利 世界500强threeDays2020/3/14 22:39478564311号线滨和路1号线_滨和路;1号线_江陵路;1号线_滨和路;1号线_江陵路30.208562120.219225NaN631000.256719NaNNaNNaN00NaN000NaNNaN00[]False
1036704835BI数据分析师52840i/image2/M00/26/CA/CgoB5lofsguAfk9ZAACoL3r4p24...2000人以上电商上市公司['技能培训', '年底双薪', '节日礼物', '绩效奖金']开发|测试|运维类数据开发数据分析['SQLServer', '数据分析']['电商', '新零售', 'SQLServer', '数据分析']['电商', '新零售', 'SQLServer', '数据分析']2020/3/9 15:002020/3/9余杭区['仓前']200003-5年全职本科阿里巴巴;商业智能;threeDays2020/3/16 10:1558463501NaNNaNNaN30.280177120.023521['16薪', '一年调薪2次']00000.281062NaNNaNNaN00NaN000NaNNaN00[]True
1046728058数据分析专家-LQ(J181203029)2474i/image2/M01/14/4D/CgoB5lyq5fqAAHHzAAAa148hbk8...2000人以上汽车丨出行不需要融资['弹性工作', '节日礼物', '岗位晋升', '技能培训']产品|需求|项目类数据分析其他数据分析[]['滴滴']['滴滴']2020/3/13 18:243天前发布西湖区NaN215005-10年全职本科广阔平台诱人福利disabled2020/3/13 19:5167994951NaNNaNNaN30.290746120.074315NaN00000.159343NaNNaNNaN00NaN000NaNNaN00[]True

105 rows × 53 columns

111.查找secondType与thirdType值相等的行号

np.where(df.secondType == df.thirdType)
(array([  0,   2,   4,   5,   6,  10,  14,  23,  25,  27,  28,  29,  30,
         33,  37,  38,  39,  40,  41,  48,  49,  52,  53,  55,  57,  61,
         65,  66,  67,  71,  73,  74,  75,  79,  80,  82,  85,  88,  89,
         91,  96, 100], dtype=int64),)

112.查找薪资大于平均薪资的第三个数据

df[df['salary'] > df['salary'].mean()]['salary'].index[2]
5

113.将上一题数据的salary列开根号

df[['salary']].apply(np.sqrt)
salary
0193.649167
1122.474487
259.160798
3212.132034
4173.205081
......
100158.113883
101187.082869
102173.205081
103141.421356
104146.628783

105 rows × 1 columns

114.将上一题数据的linestaion列按_拆分

df['split'] = df['linestaion'].str.split('_')
df['linestaion'].tail()
100                                NaN
101                                NaN
102    1号线_滨和路;1号线_江陵路;1号线_滨和路;1号线_江陵路
103                                NaN
104                                NaN
Name: linestaion, dtype: object
df.tail()
positionIdpositionNamecompanyIdcompanyLogocompanySizeindustryFieldfinanceStagecompanyLabelListfirstTypesecondTypethirdTypeskillLablespositionLablesindustryLablescreateTimeformatCreateTimedistrictbusinessZonessalaryworkYearjobNatureeducationpositionAdvantageimStatelastLoginpublisherIdapprovesubwaylinestationnamelinestaionlatitudelongitudehitagsresumeProcessRateresumeProcessDayscorenewScorematchScorematchScoreExplainqueryexplainisSchoolJobadWordpluspcShowappShowdelivergradeDescriptionpromotionScoreExplainisHotHirecountaggregatePositionIdsfamousCompanysplit
1006884346数据分析师21236i/image/M00/43/F6/CgqKkVeEh76AUVPoAAA2Bj747wU6...500-2000人移动互联网,医疗丨健康C轮['技能培训', '年底双薪', '节日礼物', '绩效奖金']产品|需求|项目类数据分析数据分析['数据库', '商业', '数据分析', 'SQL']['医疗健康', '数据库', '商业', '数据分析', 'SQL']['医疗健康', '数据库', '商业', '数据分析', 'SQL']2020/3/11 16:452020/3/11萧山区NaN250003-5年全职不限大牛老板,开放环境,民生行业,龙头公司threeDays2020/3/16 09:4916651671NaNNaNNaN30.203078120.247069NaN961000.314259NaNNaNNaN00NaN000NaNNaN00[]FalseNaN
1016849100商业数据分析72076i/image2/M01/92/A4/CgotOV2LPUmAR_8dAAB_DlDMiXA...500-2000人移动互联网,电商C轮['节日礼物', '股票期权', '带薪年假', '年度旅游']市场|商务类市场|营销商业数据分析['市场', '数据分析', '行业分析', '市场分析']['电商', '市场', '数据分析', '行业分析', '市场分析']['电商', '市场', '数据分析', '行业分析', '市场分析']2020/3/14 17:382天前发布余杭区NaN350001-3年全职硕士五险一金、带薪休假threeDays2020/3/14 17:3817324161NaNNaNNaN30.276694119.990918NaN23000.283276NaNNaNNaN00NaN000NaNNaN00[]FalseNaN
1026803432奔驰·耀出行-BI数据分析专家751158i/image3/M01/64/93/Cgq2xl48z2mAeYRoAAD6Qf_Jeq8...150-500人移动互联网不需要融资[]开发|测试|运维类数据开发数据分析['MySQL', '数据处理', '数据分析']['MySQL', '数据处理', '数据分析'][]2020/3/14 22:392天前发布滨江区['西兴']300003-5年全职本科奔驰 吉利 世界500强threeDays2020/3/14 22:39478564311号线滨和路1号线_滨和路;1号线_江陵路;1号线_滨和路;1号线_江陵路30.208562120.219225NaN631000.256719NaNNaNNaN00NaN000NaNNaN00[]False[1号线, 滨和路;1号线, 江陵路;1号线, 滨和路;1号线, 江陵路]
1036704835BI数据分析师52840i/image2/M00/26/CA/CgoB5lofsguAfk9ZAACoL3r4p24...2000人以上电商上市公司['技能培训', '年底双薪', '节日礼物', '绩效奖金']开发|测试|运维类数据开发数据分析['SQLServer', '数据分析']['电商', '新零售', 'SQLServer', '数据分析']['电商', '新零售', 'SQLServer', '数据分析']2020/3/9 15:002020/3/9余杭区['仓前']200003-5年全职本科阿里巴巴;商业智能;threeDays2020/3/16 10:1558463501NaNNaNNaN30.280177120.023521['16薪', '一年调薪2次']00000.281062NaNNaNNaN00NaN000NaNNaN00[]TrueNaN
1046728058数据分析专家-LQ(J181203029)2474i/image2/M01/14/4D/CgoB5lyq5fqAAHHzAAAa148hbk8...2000人以上汽车丨出行不需要融资['弹性工作', '节日礼物', '岗位晋升', '技能培训']产品|需求|项目类数据分析其他数据分析[]['滴滴']['滴滴']2020/3/13 18:243天前发布西湖区NaN215005-10年全职本科广阔平台诱人福利disabled2020/3/13 19:5167994951NaNNaNNaN30.290746120.074315NaN00000.159343NaNNaNNaN00NaN000NaNNaN00[]TrueNaN

115.查看上一题数据中一共有多少列

df.shape[1]
54

116.提取industryField列以’数据’开头的行

df[df['industryField'].str.startswith('数据')].tail()
positionIdpositionNamecompanyIdcompanyLogocompanySizeindustryFieldfinanceStagecompanyLabelListfirstTypesecondTypethirdTypeskillLablespositionLablesindustryLablescreateTimeformatCreateTimedistrictbusinessZonessalaryworkYearjobNatureeducationpositionAdvantageimStatelastLoginpublisherIdapprovesubwaylinestationnamelinestaionlatitudelongitudehitagsresumeProcessRateresumeProcessDayscorenewScorematchScorematchScoreExplainqueryexplainisSchoolJobadWordpluspcShowappShowdelivergradeDescriptionpromotionScoreExplainisHotHirecountaggregatePositionIdsfamousCompanysplit
926813626资深数据分析专员165939i/image3/M01/65/71/CgpOIF5CFp2ACoo9AAD3IkKwlv8...150-500人数据服务不需要融资['年底双薪', '带薪年假', '午餐补助', '定期体检']开发|测试|运维类数据开发数据分析['数据分析']['数据分析'][]2020/3/15 12:211天前发布余杭区NaN300003-5年全职不限阿里旗下、大数据today2020/3/15 13:1385198051NaNNaNNaN30.281507120.018621NaN11100.440405NaNNaNNaN00NaN000NaNNaN00[]FalseNaN
946818950资深数据分析师165939i/image3/M01/65/71/CgpOIF5CFp2ACoo9AAD3IkKwlv8...150-500人数据服务不需要融资['年底双薪', '带薪年假', '午餐补助', '定期体检']开发|测试|运维类数据开发数据分析['数据分析']['数据分析'][]2020/3/15 12:211天前发布余杭区NaN300005-10年全职不限阿里旗下、大数据today2020/3/15 13:1385198051NaNNaNNaN30.281507120.018621NaN11100.407209NaNNaNNaN00NaN000NaNNaN00[]FalseNaN
976718750旅游大数据分析师(杭州)122019i/image/M00/1A/4A/CgqKkVb583WABT4BAABM5RuPCmk9...50-150人数据服务,企业服务A轮['年底双薪', '股票期权', '午餐补助', '定期体检']开发|测试|运维类数据开发数据治理['数据分析', '数据处理']['旅游', '大数据', '数据分析', '数据处理']['旅游', '大数据', '数据分析', '数据处理']2020/3/12 16:382020/3/12上城区['湖滨', '吴山']300001-3年全职本科管理扁平 潜力项目 五险一金 周末双休sevenDays2020/3/13 08:481134763012号线中河北路1号线_定安路;1号线_龙翔桥;1号线_凤起路;1号线_定安路;1号线_龙翔桥;1号线_凤起...30.254169120.164651NaN30100.826756NaNNaNNaN00NaN000NaNNaN00[]False[1号线, 定安路;1号线, 龙翔桥;1号线, 凤起路;1号线, 定安路;1号线, 龙翔桥;...
986655562数据分析建模工程师117422215i/image2/M01/AF/6D/CgotOV3ki4iAOuo3AABbilI8DfA...50-150人数据服务,信息安全A轮['午餐补助', '带薪年假', '16到18薪', '法定节假日']开发|测试|运维类人工智能机器学习['机器学习', '建模', '数据挖掘', '算法']['机器学习', '建模', '数据挖掘', '算法'][]2020/3/14 19:002天前发布西湖区NaN300001-3年全职本科海量数据 全链路建模实践 16-18薪threeDays2020/3/16 09:30881033612号线丰潭路2号线_古翠路;2号线_丰潭路30.291494120.113955NaN00000.356308NaNNaNNaN00NaN000NaNNaN00[]False[2号线, 古翠路;2号线, 丰潭路]
996677939数据分析建模工程师(校招)117422215i/image2/M01/AF/6D/CgotOV3ki4iAOuo3AABbilI8DfA...50-150人数据服务,信息安全A轮['午餐补助', '带薪年假', '16到18薪', '法定节假日']开发|测试|运维类人工智能算法工程师['机器学习', '建模', '算法', '数据挖掘']['机器学习', '建模', '算法', '数据挖掘'][]2020/3/14 19:002天前发布西湖区NaN36500应届毕业生全职本科海量数据 全链路建模实践 16-18薪threeDays2020/3/16 09:30881033612号线丰潭路2号线_古翠路;2号线_丰潭路30.291494120.113955NaN00000.338603NaNNaNNaN10NaN000NaNNaN00[]False[2号线, 古翠路;2号线, 丰潭路]

117.按列制作数据透视表

pd.pivot_table(df,values=["salary","score"],index="positionId")
salaryscore
positionId
5203054300004.0
520491215000176.0
5269002375001.0
5453691300004.0
55199623750014.0
.........
68829832750015.0
6884346250000.0
6886661375005.0
6888169425001.0
6896403300003.0

95 rows × 2 columns

118.同时对salary、score两列进行计算

df[["salary","score"]].agg([np.sum,np.mean,np.min])
salaryscore
sum3.331000e+061335.000000
mean3.172381e+0412.714286
amin3.500000e+030.000000

119.对salary求平均,对score列求和

df.agg({"salary":np.sum,"score":np.mean})
salary    3.331000e+06
score     1.271429e+01
dtype: float64

120.计算并提取平均薪资最高的区

df[['district','salary']].groupby(by='district').mean().sort_values('salary',ascending=False).head(1)
salary
district
萧山区36250.0

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值