1. Pandas简介
Pandas基于Numpy实现,扩展数据类型,更关注数据与索引之间的关系; Pandas可以处理各种文件格式,CSV文件、JSON文件、XML文件、Parquet文件、SQL文件 Pandas提供两个数据类型:Series,DataFrame 官方文档:https://pandas.pydata.org/pandas-docs/stable/index.html 中文文档:https://www.pypandas.cn/docs/
2. Pandas类型
2.1 Series类型
一组(列)数据和其相关的数据索引组成,索引在左边值在右边,可以通过索引访问; 可以保存任何类型数据(int/str/float/obj…)的一维数组; 如果没指定索引,会自动创建一个0到n-1的整数型索引,也可以使用index指定索引
ser = pd. Series( [ 9 , 8 , 7 , 6 , 5 ] )
print ( ser)
> 0 9
1 8
2 7
3 6
4 5
dtype: int64
ser = pd. Series( range ( 5 ) , index= [ 'a' , 'b' , 'c' , 'd' , 'e' ] )
print ( ser)
> a 0
b 1
c 2
d 3
e 4
dtype: int64
ser = pd. Series( np. array( [ 1 , 2 , 3 ] ) )
print ( ser)
> 0 1
1 2
2 3
dtype: int64
ser = pd. Series( { 'name' : '张三' , 'age' : 18 , 'sex' : 'F' , 'hobby' : '足球' } )
print ( ser)
> name 张三
age 18
sex F
hobby 足球
dtype: object
2.2 DataFrame类型
表格型的数据结构,一组有序的列数据和其共用的索引组成,每列可以是不同的值类型(数值、字符串、布尔值等); DataFrame既有行索引也有列索引,列可以通过列名访问,行通过索引访问
list = [ [ 12 , 14 , 16 , 18 ] , [ 2 , 4 , 6 , 8 ] , [ 22 , 24 , 26 , 28 ] ]
df = pd. DataFrame( list , columns = [ 'a' , 'b' , 'c' , 'd' ] , index = [ 11 , 22 , 33 ] )
print ( df)
> a b c d
11 12 14 16 18
22 2 4 6 8
33 22 24 26 28
data = { 'name' : [ '陈大' , '钱二' , '张三' , '李四' ] ,
'age' : [ 25 , 27 , 26 , 23 ] ,
'sex' : [ '男' , '女' , '男' , '男' ] ,
'hobby' : [ '足球' , '篮球' , '羽毛起' , '乒乓球' ] ,
'height' : [ 180 , 167 , 145 , 187 ] }
df = pd. DataFrame( data)
print ( df)
> name age sex hobby height
0 陈大 25 男 足球 180
1 钱二 27 女 篮球 167
2 张三 26 男 羽毛起 145
3 李四 23 男 乒乓球 187
name age sex hobby height 0 陈大 25 男 足球 180 1 钱二 27 女 篮球 167 2 张三 26 男 羽毛起 145 3 李四 23 男 乒乓球 187
3. pandas操作
3.1 数据查询
df
df. info
df. head( 2 )
df. tail( 1 )
df. index
df. columns
df. values
df. describe( )
df. to_numpy( )
df. T
df. sort_index( axis= 1 , ascending= False )
df. sort_values( by= 'age' )
df.name # 同df['name'],选择单列,生成Series,
# iloc 基于位置来选择数据
df.iloc[2] # 取第3行,
df.iloc[:,2] # 取第3列,
df.iloc[2,2] # 取第3行第3列,
df.iloc[1:3,1:3] # 取第1-3行的第1-3列,
# loc 基于标签来选择数据
df.loc[df['name']== '陈大'] # 选择name='陈大'的行,
df.loc[2:4, ['name','height']] # 行切片后选择特定列,
df.loc[2, ['name','height']] # 选择行的特定列,
df.loc[df['name']== '陈大', ['name','height']] # 选择name='陈大'的行的特定列
csv文件操作
df = pd. read_csv( "tmp/nbt/0623.csv" , dtype= str , keep_default_na= True , skip_blank_lines= True )
df = df. dropna( axis= 0 , how= 'all' )
df = df. dropna( axis= 1 , how= 'all' )
df. fillna( "" , inplace= True )
merged_df = df1. merge( df2[ [ "border_id" , "match_lane_type" ] ] , left_on= "pred_mark_id" , right_on= "border_id" , how= "left" )
merged_df = pd. concat( [ df1, df2] , ignore_index= True )
df = df. drop_duplicates( )
df. to_csv( file_path, index= False )
def merge_rows ( group, group_field) :
result = group. iloc[ 0 ] . copy( )
for col in group. columns:
if col != group_field:
unique_values = group[ col] . unique( )
if len ( unique_values) == 1 :
result[ col] = unique_values[ 0 ]
else :
result[ col] = ',' . join( map ( str , unique_values) )
return result
def csv_merge_rows_by_group ( input_file, output_file, group_field) :
df = pd. read_csv( input_file)
merged_df = df. groupby( group_field) . apply ( lambda x: merge_rows( x, group_field) ) . reset_index( drop= True )
merged_df. to_csv( output_file, index= False )
import os
import pandas as pd
def merge_csv_to_excel ( target_dir, excel_file) :
csv_files = [ os. path. join( target_dir, f) for f in os. listdir( target_dir) if f. endswith( '.csv' ) ]
with pd. ExcelWriter( excel_file, engine= 'openpyxl' ) as writer:
for csv_file in csv_files:
df = pd. read_csv( csv_file, low_memory= False )
df = df. drop_duplicates( )
sheet_name = os. path. splitext( os. path. basename( csv_file) ) [ 0 ]
print ( sheet_name, df. match_result. value_counts( ) )
df. to_excel( writer, sheet_name= sheet_name, index= False )