【Python】【Numpy+Pandas数据处理·闯关】和鲸社区学习笔记day(2)

1.创建DataFrame

data = {
    
    "col1":['Python', 'C', 'Java', 'R', 'SQL', 'PHP', 'Python', 'Java', 'C', 'Python'],
       "col2":[6, 2, 6, 4, 2, 5, 8, 10, 3, 4], 
       "col3":[4, 2, 6, 2, 1, 2, 2, 3, 3, 6]}
df = pd.DataFrame(data)
df
col1 col2 col3
0 Python 6 4
1 C 2 2
2 Java 6 6
3 R 4 2
4 SQL 2 1
5 PHP 5 2
6 Python 8 2
7 Java 10 3
8 C 3 3
9 Python 4 6

2. 设置索引

df['new_index'] = range(1,11)
df.set_index('new_index')
col1 col2 col3
new_index
1 Python 6 4
2 C 2 2
3 Java 6 6
4 R 4 2
5 SQL 2 1
6 PHP 5 2
7 Python 8 2
8 Java 10 3
9 C 3 3
10 Python 4 6

3.更改列名

#方法二:(使用rename()函数:修改指定修改某列或某几列名字)
df.rename(columns={
    
    'col1':'grammer', 'col2':'score', 'col3':'cycle','new_index':'id'}, inplace=True)
df.head()
grammer score cycle id
0 Python 6 4 1
1 C 2 2 2
2 Java 6 6 3
3 R 4 2 4
4 SQL 2 1 5

4.更改全部列顺序

order = df.columns[[0, 3, 1, 2]] # 或者order = ['xx', 'xx',...] 具体列名
df = df[order]
df
score id grammer cycle
0 6 1 Python 4
1 2 2 C 2
2 6 3 Java 6
3 4 4 R 2
4 2 5 SQL 1
5 5 6 PHP 2
6 8 7 Python 2
7 10 8 Java 3
8 3 9 C 3
9 4 10 Python 6

5.提取第一列位置在1,10,15上的值

# 方法一:
df.iloc[[1,10,15], 0]
# 方法二:
df['createTime'][[1,10,15]]
# 方法三:
df['createTime'].take([1,10,15])

out:
1 2020-03-16 10:58:48
10 2020-03-16 10:34:19
15 2020-03-16 10:52:14
Name: createTime, dtype: datetime64[ns]

6.判断数据框中所有行是否存在重复

df.duplicated()

7. 判断education列和salary列数据是否重复(多列组合查询)

df.duplicated(subset = ['education','salary'])

8.提取value列元素值大于60小于70的行

df[(df['value'] > 60) & (df['value'] < 70)]

9.提取salary列包含字符串(‘–’)的行

# 方法一:isin()
df[df['salary'].isin(['--'])]
# 方法二:contains()
df[df["salary"].str.contains("--")]

10.提取value列和value1列出现频率最高的数字

# 先将两列使用append()按行合并,再用计数函数:
temp = df['value'].append(df['value1'])
temp.value_counts(ascending=False)#不加index,返回的是一个Series
temp.value_counts(ascending=False).index[:5] #返回一个数组

作业

import pandas as pd
import numpy as np
import re

data = pd.read_excel(r'pandas120.xlsx')
df = pd.DataFrame(data)

# 提取学历为本科,工资在25k-35k的数据

df1 = df.loc[df['education'].isin(['本科']) & df['salary'].isin(['25k-35k']), :]

# 提取salary列中以'40k'结尾的数据

df2 = df[df['salary'].str.endswith('40k')]

# 提取薪资区间中最低薪资与最高薪资的平均值大于30k的行,只需提取原始字段('createTime', 'education', 'salary')即可

salary = df
tmp = salary['salary'].str.extract(r'(\d+).*?(\d+)') # 正则匹配,分割字符串
salary['avg'] = ((tmp[0].astype('int') + tmp[1].astype('int')) / 2) # 切记 相加记得加小括号
df3 = salary[salary['avg'] > 30]
df3 = df3.drop(columns=['avg'])


# 将以上三题提取出来的行按照相同列进行合并,汇总到一个数据框中

answer_2 = pd.concat([df1, df2, df3], axis=0)

# 将三列数据合并成一列,并设置列名为answer,最后保留id(数据行数、answer)

data = pd.concat([answer_2.iloc[:, 0], answer_2.iloc[:, 1], answer_2.iloc[:, 2]])
df = pd.DataFrame(data, columns=['answer'])
df['id'] = range(len(df))
df = df[['id', 'answer']]

# 将结果保存为 csv 文件

df.to_csv(r'answer_2.csv', index=False, encoding='utf-8-sig')

收获

  • · inplace = True表示在原DataFrame上进行操作 · pf.columns[索引]返回的是一个Index列表,可以用来作为.iloc[]的参数

  • · Pandas的insert()函数允许用户在指定的位置插入行和列。下面是insert()函数的语法:
    DataFrame.insert(loc, column, value, allow_duplicates=False)
    参数说明:
    • loc:表示要插入的数据的位置,以整数形式表示。
    • column:要插入的列名(如果未指定值,则必须传递列名)
    • value:要插入的值。可以是单个值或一组值。
    • allow_duplicates:如果设为True时,允许在同一位置上重复列名。
    ps:已经存在的列的列名不能重复添加

  • · DataFrame对象
    take函数是一个用于返回指定的行的函数。
    语法:DataFrame.take(indices, axis=0, convert=None):
    参数:
    • indices:行的索引值(int或者list of ints)。
    • axis:可选参数,默认值为0。
    • convert: 可选参数,默认值为None。是否将索引转换为相应的列标签。
    返回:Ndarray或者其他可迭代对象中存储的行元素。

  • ·df.[] 里面也能对type为Series,数据为bool进行df数据筛选

猜你喜欢

转载自blog.csdn.net/qq_25218219/article/details/129466585