DataFrame的一般操作

  • *1.DataFrame对象的生成
pandas.DataFrame(data,index,columns,dtype,copy)

1.data:支持多种数据类型

2.index:行标签,如果没有传递,则默认为0,1,2,3…

3.columns:列标签,如果没有传递,则默认为0,1,2,3…

4.dtype:每列的数据类型

5.copy:是否复制数据,默认值为false

  • *从列表创建DataFrame

1.一维列表创建DataFrame

import pandas as pd
data=[1,2,3,4,5]
df=pd.DataFrame(data)
print(df)

'''
    0
0   1
1   2
2   3
3   4
4   5
'''

2.二维列表创建DataFrame,并指定数据类型

import pandas as pd
data=[['alex',10],['bob',12],['clarke',13]]
df=pd.DataFrame(data,columns=['name','age'],dtype=int)   #指定了dtype
print(df)

'''
     name  age
0    alex  10
1    bob   12
2    clarke 13
'''
  • 从ndarray/list的字典来创建DataFrame, *不传入columns的话,字典中的key代替了DateFrame中的columns,values代替了DataFrame中该columns的值
import pandas as pd
data={'name':['tom','jack','steve'],'age':[17,18,19]}
df1=pd.DataFrame(data)
print(df1)
'''
    name   age
0    tom    17
1    jack   18
2    steve  19
'''
df2=pd.DataFrame(data,columns=['NAME','AGE'])
print(df2)
'''
    NAME  AGE
0    tom    17
1    jack   18
2    steve  19
'''
  • *传递字典列表来创建DataFrame
import pandas as pd
data=[{'a':1,'b':2},{'a':5,'b':10,'c':20}]
df1=pd.DataFrame(data)
print(df1)

'''
    a  b  c
0   1  2  NaN
1   5  10  20
'''

#插入index后
df2=pd.DataFrame(data,index=['first','second'])
print(df2)
'''
        a  b  c
first   1  2  NaN
second  5  10  20
'''
#插入columns后,列会对key值进行一个筛选,然后输出,没有的columns则整列返回NaN
df3=pd.DataFrame(data,index=['first','second'],columns=['a','b','d')
print(df3)

'''
        a  b   d
first   1  2   NaN
second  5  10  NaN

'''
  • *插入columns后,列会对key值进行一个筛选,然后输出,没有的columns则整列返回NaN

  • *从Series字典创建DataFrame

import pandas as pd
d={'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,3,4],index=
      ['a','b','c','d'])}
df=pd.DataFrame(d)
print(df)
'''
    one  two
a    1.0  1
b    2.0  2
c    3.0  3
d    NaN  4'''
  • *2.DataFrame对象的使用

  • 读取列

import pandas as pd
d={'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,3,4],index=
      ['a','b','c','d'])}
df=pd.DataFrame(d)
print(df['one])
'''
a  1
b  2
c  3
d  NaN
'''
  1. 添加列
import pandas as pd
d={'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,3,4],index=
      ['a','b','c','d'])}
df=pd.DataFrame(d)
df['three']=pd.Series([10,20,30],index=['a','b','c'])#通过此行追加列,并添加此列数据和设置索引
print(df)
'''
    one  two   three
a    1.0  1     10
b    2.0  2     20
c    3.0  3     30
d    NaN  4     NaN

'''
  1. 删除列
import pandas as pd
d={'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,3,4],index=
      ['a','b','c','d'])}
df=pd.DataFrame(d)
df['three']=pd.Series([10,20,30],index=['a','b','c'])
#1.使用del命令
del df['one']   #删除columns为one的列

#2.使用pop命令
df.pop('two')   #删除columns为two的列
  1. 读取行
import pandas as pd
d={'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,3,4],index=
      ['a','b','c','d'])}
df=pd.DataFrame(d)
#1.按索引选择   loc
df.loc['b']
'''
one 2.0
two 2.0
name:b,dtype:float64
'''
#2.按位置选择    iloc
df.iloc[2]
'''
one 3.0
two 3.0
name:c,dtype:float64'''

#按切片选择
df[2:4]
'''
    one  two
c    3.0   3
d    NaN   4
  1. 添加行
import pandas as pd
df=pd.DataFrame([[1,2],[3,4]],columns=['a','b'])
df2=pd.DataFrame([[5,6],[7,8]],columns=['a','b'])
df=df.append(df2)
'''
   a   b
0  1   2
1  3   4
0  5   6
1  7   8
'''
df.append(other,ignore_index=False,verity_integrity=False,sort=False)
other:要附加的数据,DataFrame或者Series等类型
ignore_index:如果是True,则不使用索引标签,默认为false
verity_integrity:如果是true,在创建于重复项的索引时,引发valueError,默认为false
sort:如果原数据和添加数据的列没有对齐,则对列进行排序,不建议排序'''
  1. 删除行
import pandas as pd
df=pd.DataFrame([[1,2],[3,4]],columns=['a','b'])
df=df.drop(0)     #此处删除了index为0的行,即下方运行结果
print(df)
'''
    a   b
1   3   4
'''

3.DataFrame的属性和方法

| T | 转置行和列 |
| axes | 返回一个列,行轴标签和列轴标签作为唯一的成员 |
| dtypes | 返回此对象中的数据类型 |
| empty | 如果DataFrame为空,则返回为True,任何轴的长度都为0 |
| ndim | 数组维度大小,默认为2维 |
| shape | 返回表示DataFrame的维度的元组 |
| size | DataFrame中的元素个数 |
| values | 将DataFrame中的实际数据作为NDarray返回 |
| head() | 返回开头n行 |
| tail() | 返回最后n行 |

因以上属性和方法通俗易懂,在此,就列举一二

import pandas as pd
df=pd.DataFrame([[1,2],[3,4]],columns=['a','b'])
print(df.T)
'''
    0   1
a   1   3
b   2   4'''
print(df.values)
'''
[[1,2]
 [3,4]]'''

4.DataFrame函数应用

| count() | 非空数据的数量 |
| ——— | —————- |
| sum() | 所有值之和 |
| mean() | 所有值的平均值 |
| median() | 所有值的中位数 |
| mod() | 值的模 |
| std() | 值的标准偏差 |
| min() | 所有值中的最小值 |
| max() | 所有值中的最大值 |
| abs() | 绝对值 |
| prod() | 数组元素的乘积 |
| cumsum() | 累计总和 |
| cumprod() | 累计乘积 |

import pandas as pd
data={'name':pd.Series(['jack','tom','jerry'],index=
      ['a','b','c']),'age':pd.Series([18,19,20],index=['a','b','c'])}
df=pd.DataFrame(data)
'''
    name   age
a   jack    18
b   tom     19
c   jerry   20'''

print(df.sum())   #返回所请求轴的值的总和,默认情况下axis=0
'''
name  jacktomjerry
age    47
dtype:object'''

print(df.sum(1))    #按行进行求和
'''
a   18
b   19
c   20
dtype:int32'''

df.describe(include=[”])#用来计算有关DataFrame列的统计信息摘要

object:汇总字符串列

number:汇总数字列

all:将所有列汇总在一起(不应将其作为列表值传递)

df.describe(include=['object'/'number']/'all']

| lower() | 将Series/Index中的字符串转换为小写 |
| ——————- | ———————————————————— |
| upper() | 将Series/Index中的字符串转换为大写 |
| len() | 计算字符串长度 |
| strip() | 帮助从两侧的系列/索引中的每个字符串中删除空格(包括换行符) |
| split(‘ ‘) | 用给定的模式拆分每个字符串 |
| cat(sep=’ ‘) | 使用给定的分隔符连接系列/索引元素 |
| get_dummies() | 返回具有单热编码值的数据帧(DataFrame) |
| contains(pattern) | 如果元素中包含子字符串,则返回每个元素的布尔值True,否则为False |
| replace(a,b) | 将值a替换为值b |
| repeat(value) | 重复每个元素指定的次数 |
| count(pattern) | 返回模式中每个元素的出现总数 |
| startswith(pattern) | 如果系列/索引中的元素以模式开始,则返回true |
| endswith(pattern) | 如果系列/索引中的元素以模式结束,则返回true |
| find(pattern) | 返回模式第一次出现的位置 |
| findall(pattern) | 返回模式的所有出现的列表 |
| swapcase() | 变换字母大小写 |
| islower() | 检查系列/索引中每个字符串中的所有字符是否小写,返回布尔值 |
| isupper() | 检查系列/索引中每个字符串中的所有字符是否大写,返回布尔值 |
| isnumeric() | 检查系列/索引中每个字符串中的所有字符是否为数字,返回布尔值 |

import pandas as pd
import numpy as np
s=pd.Series(['tom','Willim Rick','Jorn','Alpha','1234'])
print(s)
'''
0  tom
1  willim Rick
2  Jorn
3  Alpha
4  1234
'''

print(s.str.split('i')   #按什么拆分,先把Series类型转换成str类型再调用方法
'''
0  [tom]
1  [w,ll,m R,ck]
2  [Jorn]
3  [Alpha]
4  [1234]
dtype:object
'''
print(s.str.cat(sep='='))
'''
tom=willim Rick=Jorn=Alpha=1234'''

print(s.str.contains('i'))    #判断元素中是否有i子字符串
'''
0  false
1  true
2  false
3  false
4  false
'''
print(s.str.endwith('k'))   #判断每个元素末尾是否以k结束
'''
0   false
1   true
2   false
3   false
4   false
'''

print(s.str.find('m'))   #判断每个元素中传入的子字符串所在的位置
'''
0  2
1  5
2  -1
3  -1
4  -1'''

'''

把数据放到函数中进行应用/转换,成我们想要的数据

pipe(func,args,kwargs)
func:函数
args,kwargs:意味着,我们自定义函数需要多个参数的时候可以进行传递
——————————————————————————————————————————
apply(func,axis= 0,raw= False,result_type=None,args=(),
kwargs)
func:作用于每一行和每一列
axis:所对应的轴,默认是0
0或者index:代表每一列
1或者columns:代表每一行
raw:布尔类型,默认是False
如果时False:将每一行和每一列作为Series传递给函数
如果时True:将数据作为ndarry传递给函数
result_type : {‘expand’, ‘reduce’, ‘broadcast’, None},默认是none
expand:类似列表的结果转换成DataFrame的列
reduce:如果可能,返回一个Series或DataFrame,而不是类似列表的结果,和expand相反
broadcast:结果保留原始索引和列

———————————————————————————————————————————

使用applymap,那么df是一个整体

import pandas as pd
import numpy as np
#表式函数应用  pipe()
def adder(ele1,ele2):
    return ele1+ele2
df=pd.Dataframe(np.arange(9).reshape(3,3),columns=['col1','col2','col3'])
data=df.pipe(adder,2)
'''
   col1   col2   col3
0   2      3      4
1   5      6      7
2   8      9      10
'''

#行和列函数应用
df=pd.Dataframe(np.arange(9).reshape(3,3),columns=['col1','col2','col3'])
data=df.apply(np.mean)
'''col1   5
col2   6
col3   7'''

#元素函数应用
df=pd.DataFrame(np.random.randint(10,size=(3,3)),columns=['col1','col2','col3'])
data=df['col1'].map(lambda x:x*100)
print(data)
'''
0    200
1    500
2    100
Name: col1, dtype: int64'''

Original: https://blog.csdn.net/weixin_53591842/article/details/121845804
Author: 蔡叔叔two
Title: DataFrame的一般操作

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/674153/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球