python dataframe 和 函数

时间:2024-10-25 08:05:49

python dataframe函数

主要是介绍dataframe和python常数常用的

所有使用到的包

from cmath import isnan
from typing import List
import requests,json,pandas as pd,time,numpy as np,pymysql,os,configparser,datetime,re,random
from sqlalchemy import create_engine
from lxml import etree
from requests.adapters import HTTPAdapter
from queue import Queue
from difflib import SequenceMatcher#导入库
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Merge

合并,将两个dataframe进行合并相当于sql中的表连接(left join ,inner join ,right join等)

df = pd.merge(df1, df2, how='left', on=['id'])
  • 1

ps : 函数名字
-------- df1、df2 dataframe
-------- how 那种链接方式
-------- on 连接条件

Rename

重命名,修改dataframe中的表头名 : 将id修改为iid

df.rename(columns={'id':'iid'},inplace=True)
  • 1

创建Dataframe

创建指定字段的空白的Dataframe

df = pd.DataFrame(columns=['url','reg','city','floor_name','address','business','code','date','area','buil_co','room_sum'])
  • 1

根据数据创建Dataframe,并将字符串添加到Dataframe中

new=pd.DataFrame({'url':chil_url,'reg':reg,'city':city_name,'floor_name':fang_name,'address':location,'business':busniss,'code':code,'date':start_date,'area':area,'buil_co':buil_co,'room_sum':room_num},index=[0])
  • 1

根据数据创建Dataframe的另外一种写法

df = pd.DataFrame([[qqqq,bbb,ccc]],columns=('111','222','333'))
  • 1

根据数据创建Dataframe的第三种写法

data = [
    ['aaaaa','bbbbb','ccc'],
    ['aaaaa','bbb','cccc']
]
df = pd.DataFrame(data, columns=['hhhh', 'rrrrr', 'tttt'])
  • 1
  • 2
  • 3
  • 4
  • 5

单引号里的为字段名称
冒号后边跟的是变量名
index=[0] : 指定索引为0
示例 : new_df = pandas.DataFrame({‘column_name1’: ‘String1’,‘column_name2’: ‘String2’,…},index=[0])

dff = pd.DataFrame([[fang_id,fang_name,bk_name,dongtai,provide_title,date,provide_sche]],columns=('fang_id','fang_name','bk_name','dongtai','provide_title','date','provide_sche'))
  • 1

中括号内的是变量名称
columns后跟的是列名

日期

time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  ###当天日期
yesterday_date_time=(datetime.strptime(date_time, '%Y-%m-%d') + timedelta(days = 1)).strftime("%Y-%m-%d")  #昨天
loagoday_date_time=(datetime.strptime(date_time, '%Y-%m-%d') + timedelta(days = -1)).strftime("%Y-%m-%d")  #大前天
df_sy['quarter'] = pd.PeriodIndex(df_sy.date_clean, freq='Q') #获取当前时间的季度
  • 1
  • 2
  • 3
  • 4

截取

截取整数

截取当前字符串中的前三个数,并拼接在一起

start_date = re.findall(r'\d+',start_date )[0]+'-'+re.findall(r'\d+',start_date )[1].rjust(2,'0') +'-'+re.findall(r'\d+',start_date )[2].rjust(2,'0')
  • 1

(r’\d’,String) : 正则过滤字符串中所有数字
rjust(2,‘0’) : 保留两位,位数不够左补0
字符串示例: 2021年1月12日. 想要将字符串转换为 2021-01-12

补0

保留两位,位数不够左补0

str(1).rjust(2,'0')
  • 1
'
运行

多列分组

单列求和

df.groupby(by=['reg','city','floor_name','address','business','code','date'])['room_sum'].sum().reset_index()
  • 1

多列求和

df = df.groupby(by=['code','date']).agg({'room_sum': sum, 'area': sum}).reset_index()
  • 1

多行合并一行

单列的多行合并为一行

df.groupby(['code'])['url'].apply(list).to_frame()
  • 1

多列同时多行合并为一行

df.groupby(by=['code','date']).agg({'url':list,'buil_co':list}).reset_index()
  • 1

聚合和行合并同时进行

df.groupby(by=['code','date']).agg({'area': sum,'url':list}).reset_index()
  • 1

DataFrame 值只取整数

df['area'] = df['area'].apply(lambda x:re.sub('\D','',x))
  • 1

DataFrame 替换

data_new['buil_co']=data_new['buil_co'].apply(lambda x:str(x).replace('[','').replace(']',''))
  • 1

DataFrame 切分

df['area'] = df['area'].apply(lambda x:x.split('.')[0])
  • 1

DataFrame 灵活按照数据切分

按照数据切分,获取左边数据. 例如: 第一次hello wprld222**^%# . 获取 : 第一次hello wprld

df['area'] = df['area'].apply(lambda x: re.split('\d+',x)[0])
  • 1

主要核心思是正则和split结合使用, 还可以指定多个分割符进行分割. 都在链接里
原文链接: /shunguo/p/

DataFrame 获取单个值

ysskzh=sjz_code.iloc[0].at['code']
  • 1

DataFrame 窗口排序

df_sy.sort_values(by=['city','code'],axis = 0,ascending = False).groupby(['city'])
  • 1

DataFrame 分组下移

shift():

df_sy['last_date']=df_sy.sort_values(by=['city','code'],axis = 0,ascending = False).groupby(['city'])['date_clean'].shift(1) # 
  • 1

使用场景:
1、计算增量和存量用户,实现方法:根据用户分组,对时间进行排正序,然后下移。新的字段为空时即为增量用户,其他为存量用户
2、获取相邻数值,实现方法:根据用户分组,对时间排正序,然后下移。然后判断旧的值为空时,用下移的值替换,就能补充该用户的时间。

DataFrame获取某个值

就是筛选条件,获取df中年龄为1的第一个名字

result = df['name'][df['age']==1].values[0]
  • 1

DataFrame添加多行数据

df = pd.DataFrame([['w','9'],['z','10']],columns=['name','age'])
  • 1

DataFrame判断是否为空,为空给0

讲col1中的为空的数据替换为0

df.at[df['col1'].isna(),'col1'] = 0
  • 1

DataFrame删除某一列

df.drop(['id'],axis=1)
  • 1

DataFrame中的json转DataFrame

这里介绍两种方式,不管哪种方式都需要原始数据的格式是正确的,所以可能要先进行替换
第一种 使用 json_normalize

json_data_company = 'json数据'
df_data = pd.json_normalize(json.loads(json_data_company))
  • 1
  • 2

需要注意的: 不管哪种方法都只能一层一层的解析,如果需要解析多层就套娃.例如:
!!!以下的代码并不是全部!!!

df4 = (df3.to_json(orient = “records”,force_ascii=False)) #将DataFrame转换为json
#将json文件中错误的地方纠正
df4 = (‘:"{’,‘:{’).replace(‘}"’,‘}’).replace(‘’‘,’“')
#####转换为字典
df5 = (df4)
#####转换为DtaFrame
df6 = pd.json_normalize(df5)
#####不放过任何一条数据
# df6_tmp = df1[df1[‘top_pages_ods’] == “Document[[]]”]
# df6_tmp[‘top_pages.id_url’] =
# df6_tmp[‘top_pages.count’] =
# df6 = (df6_tmp,ignore_index=False)
######清洗 top_jump_out
df6[‘top_jump_out_ods’] = df6[‘top_jump_out’] # 留作备份查看
####将备份数据从json转为字符串形式
df6[‘top_jump_out_ods’] = df6[‘top_jump_out_ods’].map(lambda x: “Document[”+str(x)+”]“)
df6[‘top_jump_out_ods’] = df6[‘top_jump_out_ods’].map(lambda x: str(x).replace(‘:’,‘=’))
df6[‘top_jump_out_ods’] = df6[‘top_jump_out_ods’].map(lambda x: str(x).replace(‘’‘,’‘))
# #####清洗 top_pages top_jump_out,最后直接添加
# df7 = df6[df6[‘top_jump_out_ods’] != “Document[[]]”]
df7 = df6
#####去除[]转换为json
df7[‘top_jump_out’] = df7[‘top_jump_out’].map(lambda x: str(x)[1:])
df7[‘top_jump_out’] = df7[‘top_jump_out’].map(lambda x: str(x)[:-1])
#将一个 top_jump_out 拆分为多个
df7 = (‘top_jump_out’,axis=1).join(df7[‘top_jump_out’].(’}, {',expand=True).stack().reset_index(level=1,drop=True).rename(‘top_jump_out’)).reset_index(drop=True)
# top_jump_out 处理成json的样式
df7[‘top_jump_out’] = df7[‘top_jump_out’].map(lambda x: str(x)+”}“)
df7[‘top_jump_out’] = df7[‘top_jump_out’].map(lambda x: “{”+str(x).replace(‘}’,‘’).replace(‘{’,‘’).replace('‘id’: ‘value’: ‘,’‘id_value’: ')+”}“)
#将处理好的dataframe整个转为json
df8 = (df7.to_json(orient = “records”,force_ascii=False))
#将json文件中错误的地方纠正
df8 = (':”{‘,’:{‘).replace(’}“‘,’}‘).replace(’‘’,'”')
#####转换为字典
df9 = (df8)
#####转换为DtaFrame
df10 = pd.json_normalize(df9)

第二种方法 : ()

data['data'] = data['a_count'].map(lambda x: list(eval(x))) #将数据转换为列表
data = data.explode('data', ignore_index=True)              #将列表拆分为多行(一行一行的)
data = pd.DataFrame(data['data'].values.tolist())           # 转为Dataframe
  • 1
  • 2
  • 3

有些直接就是列表,不需要第一步

字符串替换 & 一个字符串中多个字符同时替换为空

两个函数:replace 、

'我是字符串1xxx'.replace('xxx','') ### 将xxx替换
re.sub('xxx','','我是字符串1xxx') ### 将xxx替换w为空
re.sub(r'我是|\d|xxx','','我是字符串1xxx') ### 分别将   我是、数字、xxx替换为空
  • 1
  • 2
  • 3

字符串中字符去重

listl = list('大大大大大大额')  # 做排序的依据
lists = list(set(listl )) # 先集合去重,在转为列表
lists.sort(key=listl.index)   # 按照listl 对 lists 进行排序
print("".join(lists))   #拼接列表为字符串
  • 1
  • 2
  • 3
  • 4
'
运行

DataFrame 拼接

#上下拼接
df.append(df1,ignore_index=False)
#左右拼接
df2 = pd.concat([df,df1],axis=1)
  • 1
  • 2
  • 3
  • 4

DataFrame 一行拆分多行

df.drop('mall',axis=1).join(df['mall'].str.split(', ',expand=True).stack().reset_index(level=1,drop=True).rename('mall')).reset_index(drop=True)
  • 1

DataFrame 列名转换为列表

df_col = df_data.columns.tolist()
  • 1

灵活删除列

df_col = df_data.columns.tolist()                                    # 列名转换为列表
tag_col = tag_name['tag_id'].values.tolist()                         # 需要保留的列名
surplus_col = [x for x in df_col if x not in tag_col ]               # 找出需要删除的列
df_data= df_data.drop(surplus_col,axis=1)                            # 删除DataFrame的列
  • 1
  • 2
  • 3
  • 4

字符串中文分词

import jieba
mytext = " ".join(jieba.cut('奥园·翡翠东湾二期花园'))
from wordcloud import WordCloud
wordcloud = WordCloud(font_path='D:/20210520/10_Tools/install/').generate(mytext)
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

字体下载地址
/notion-static/b869cb0c7f4e4c909a069eaebbd2b7ad/

语句缩写 if

## True的结果 if 条件 else False的结果
data = push_data(i) if i == 1 else data.append(push_data(i),ignore_index=True)
  • 1
  • 2