首页 > 编程语言 >PYTHON 函数 使用

PYTHON 函数 使用

时间:2023-07-12 16:57:24浏览次数:30  
标签:index 函数 PYTHON DataFrame df pd 使用 output 方法

如何使用PYTHON里的ZIP函数

a = ["Peter", "Ben", "Alice", "Jim"]
b = ["Apple", "Banana", "Pear", "Orange"]
新建两个列表,赋予不同的内容。pack = zip(a, b)
print(list(pack))

pack = zip(a, b) print(tuple(pack))
pack = zip(a, b) print(dict(pack))
当然tuple和dictionary也是可以显示的,但是结果会不一样。

for u, i in zip(a, b):
print(u, i)
用ZIP就可以在FOR LOOPS里用了。

pack2 = list(zip(a, b)) print(pack2)
当然直接这样的方式显示更直接。

for u, i in zip(a, b):
print("{} + {} = {}".format(u, i, u + i))
也可以运用在FORMAT这种形式上。

如何使用内置的map函数

f = lambda x: x * x
result = map(f, [1, 2, 3, 4]) #返回的是可迭代对象,不能直接打印出结果
print(list(result)) #要转换为 列表 ,才能打印

a=(1,2,5) b=(2,5,7)
def add(a,b):
return a+b
c,d,e = map(add,a,b) #得到 c=3 d=7 e=12 即1+2,2+5,5+7 对应相加
print([c,d,e]) [3, 7, 12]
又如:
f=lambda x,y=0,z=0:x+y+z
abc = map(f,[5,6,9],[1,2,3],[4,7,8])
list(abc)
[10, 15, 20]

reduce()函数

reduce()的使用方法形如reduce(function, iterable[, initializer]),它的形式和map()函数一样。不过参数f(x)必须有两个参数,initializer是可选的。
reduce 使用了一个二元函数(一个接收带带两个值作为输入,进行了一些计算然后返回一个值作为输出),一个序列,和一个可选的初始化器,卓有成效地将那个列表的内容"减少"为一个单一的值,如同它的名字一样。
请看实例:(注意在Python3中reduce不再是内置函数,而是集成到了functools中,需要导入)
from functools import reduce
def add(x,y):
return x+y

res= reduce(add,[1,2,3,4,5])
print(res)
结果: 15 它返回的结果相当于(1+2+3+4+5)
Reduce原理图:

它通过取出序列的头两个元素,将他们传入二元函数来获得一个单一的值来实现。然后又用这个值和序列的下一个元素来获得再下一个值,然后继续直到整个序列的内容都遍历完毕以及最后的值会被计算出来为止。

Pandas字符串函数split()

import pandas as pd
data={'brand_model': ['德力西 GW912200', '埃帝尔 IB-207TPN-06231C02', '德力西 72LT3YFM40D', '科顺 2-3654-561 铆钉型'],'cate':['低压', '管阀', '低压', '搬运']}
df_data = pd.DataFrame(data)
print(df_data)
brand_model cate
0 德力西 GW912200 低压
1 埃帝尔 IB-207TPN-06231C02 管阀
2 德力西 72LT3YFM40D 低压
3 科顺 2-3654-561 铆钉型 搬运

其中列'brand_model'需要拆分成2列:brand和model。我们看到brand和model之间是空格,所以我们可以这样来实现拆分:
df_data['brand_model'].str.split(' ', 1, expand=True)
0 1
0 德力西 GW912200
1 埃帝尔 IB-207TPN-06231C02
2 德力西 72LT3YFM40D
3 科顺 2-3654-561 铆钉型
注意:Series数据类型没有split()函数,所以需要先用.str将这一列转换为类似字符串的格式,然后再使用split()函数。然后使用merge函数连接:
pd.merge(df_data, df_data['brand_model'].str.split(' ', 1, expand=True), how='left', left_index=True, right_index=True)
brand_model cate 0 1
0 德力西 GW912200 低压 德力西 GW912200
1 埃帝尔 IB-207TPN-06231C02 管阀 埃帝尔 IB-207TPN-06231C02
2 德力西 72LT3YFM40D 低压 德力西 72LT3YFM40D
3 科顺 2-3654-561 铆钉型 搬运 科顺 2-3654-561 铆钉型

split()函数讲解:

split(self, pat=None, n=-1, expand=False)
pat:分列的依据,可以是空格,符号,字符串等等。
n:分列的次数,不指定的话就会根据符号的个数全部分列。
expand:为True可以直接将分列后的结果转换成DataFrame。
如果想要从最右边开始分列,可以使用rsplit(),rsplit()和split()的用法类似,一个从右边开始,一个从左边开始。

字符串模块string包含一些处理字符串的函数。
在用模块前必须先引入:import string
字符串模块中包含一个名为find的查找字符的函数,我们也曾写过这样的 一个例子。为了调用此函数,需利用“.”点操作符:
bookname = "new concept english"
import string
index = string.find(bookname, "s")
print index

寻找字符串中的子串开始的位置:
string.find("www.qswtp.com", "com")
10 #如果找不到,就返回-1
列表
x=[1, 2, 3]
y=x[:]
y[1]=5
x[1]
将x的值赋给y,y跟x有同样的值,但是是不同的存储空间

x=[1, 2, 3]
y=x
y[1]=5
x[1]
将x的地址值赋给y,两者有相同地址,也就具有同样的内容,一个值改变,另一个随着改变

• items()方法
• iterrows()方法
• insert()方法
• assign()方法
• eval()方法
• pop()方法
• truncate()方法
• count()方法
• add_prefix()方法/add_suffix()方法
• clip()方法
• filter()方法
• first()方法
• isin()方法
• df.plot.area()方法
• df.plot.bar()方法
• df.plot.box()方法
• df.plot.pie()方法

items()方法

pandas当中的items()方法可以用来遍历数据集当中的每一列,同时返回列名以及每一列当中的内容,通过以元组的形式,示例如下
df = pd.DataFrame({'species': ['bear', 'bear', 'marsupial'],
'population': [1864, 22000, 80000]},
index=['panda', 'polar', 'koala'])
df
output
species population
panda bear 1864
polar bear 22000
koala marsupial 80000
然后我们使用items()方法
for label, content in df.items():
print(f'label: {label}')
print(f'content: {content}', sep='\n')
print("=" * 50)
output
label: species
content: panda bear
polar bear
koala marsupial
Name: species, dtype: object

label: population
content: panda 1864
polar 22000
koala 80000
Name: population, dtype: int64

相继的打印出了‘species’和‘population’这两列的列名和相应的内容

iterrows()方法

而对于iterrows()方法而言,其功能则是遍历数据集当中的每一行,返回每一行的索引以及带有列名的每一行的内容,示例如下
for label, content in df.iterrows():
print(f'label: {label}')
print(f'content: {content}', sep='\n')
print("=" * 50)
output
label: panda
content: species bear
population 1864
Name: panda, dtype: object

label: polar
content: species bear
population 22000
Name: polar, dtype: object

label: koala
content: species marsupial
population 80000
Name: koala, dtype: object

insert()方法

insert()方法主要是用于在数据集当中的特定位置处插入数据,示例如下
df.insert(1, "size", [2000, 3000, 4000])
output
species size population
panda bear 2000 1864
polar bear 3000 22000
koala marsupial 4000 80000
可见在DataFrame数据集当中,列的索引也是从0开始的

assign()方法

assign()方法可以用来在数据集当中添加新的列,示例如下
df.assign(size_1=lambda x: x.population * 9 / 5 + 32)
output
species population size_1
panda bear 1864 3387.2
polar bear 22000 39632.0
koala marsupial 80000 144032.0
从上面的例子中可以看出,我们通过一个lambda匿名函数,在数据集当中添加一个新的列,命名为‘size_1’,当然我们也可以通过assign()方法来创建不止一个列
df.assign(size_1 = lambda x: x.population * 9 / 5 + 32,
size_2 = lambda x: x.population * 8 / 5 + 10)
output
species population size_1 size_2
panda bear 1864 3387.2 2992.4
polar bear 22000 39632.0 35210.0
koala marsupial 80000 144032.0 128010.0

eval()方法

eval()方法主要是用来执行用字符串来表示的运算过程的,例如
df.eval("size_3 = size_1 + size_2")
output
species population size_1 size_2 size_3
panda bear 1864 3387.2 2992.4 6379.6
polar bear 22000 39632.0 35210.0 74842.0
koala marsupial 80000 144032.0 128010.0 272042.0
当然我们也可以同时对执行多个运算过程
df = df.eval('''
size_3 = size_1 + size_2
size_4 = size_1 - size_2
''')
output
species population size_1 size_2 size_3 size_4
panda bear 1864 3387.2 2992.4 6379.6 394.8
polar bear 22000 39632.0 35210.0 74842.0 4422.0
koala marsupial 80000 144032.0 128010.0 272042.0 16022.0

pop()方法

pop()方法主要是用来删除掉数据集中特定的某一列数据
df.pop("size_3")
output
panda 6379.6
polar 74842.0
koala 272042.0
Name: size_3, dtype: float64
而原先的数据集当中就没有这个‘size_3’这一例的数据了

truncate()方法

truncate()方法主要是根据行索引来筛选指定行的数据的,示例如下
df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'],
'B': ['f', 'g', 'h', 'i', 'j'],
'C': ['k', 'l', 'm', 'n', 'o']},
index=[1, 2, 3, 4, 5])
output
A B C
1 a f k
2 b g l
3 c h m
4 d i n
5 e j o
我们使用truncate()方法来做一下尝试
df.truncate(before=2, after=4)
output
A B C
2 b g l
3 c h m
4 d i n
我们看到参数before和after存在于truncate()方法中,目的就是把行索引2之前和行索引4之后的数据排除在外,筛选出剩余的数据

count()方法

count()方法主要是用来计算某一列当中非空值的个数,示例如下
df = pd.DataFrame({"Name": ["John", "Myla", "Lewis", "John", "John"],
"Age": [24., np.nan, 25, 33, 26],
"Single": [True, True, np.nan, True, False]})
output
Name Age Single
0 John 24.0 True
1 Myla NaN True
2 Lewis 25.0 NaN
3 John 33.0 True
4 John 26.0 False
我们使用count()方法来计算一下数据集当中非空值的个数
df.count()
output
Name 5
Age 4
Single 4
dtype: int64

add_prefix()方法/add_suffix()方法

add_prefix()方法和add_suffix()方法分别会给列名以及行索引添加后缀和前缀,对于Series()数据集而言,前缀与后缀是添加在行索引处,而对于DataFrame()数据集而言,前缀与后缀是添加在列索引处,示例如下
s = pd.Series([1, 2, 3, 4])
output
0 1
1 2
2 3
3 4
dtype: int64
我们使用add_prefix()方法与add_suffix()方法在Series()数据集上
s.add_prefix('row_')
output
row_0 1
row_1 2
row_2 3
row_3 4
dtype: int64
又例如
s.add_suffix('row')
output
0_row 1
1_row 2
2_row 3
3_row 4
dtype: int64
而对于DataFrame()形式数据集而言,add_prefix()方法以及add_suffix()方法是将前缀与后缀添加在列索引处的
df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
output
A B
0 1 3
1 2 4
2 3 5
3 4 6
示例如下
df.add_prefix("column
")
output
column_A column_B
0 1 3
1 2 4
2 3 5
3 4 6
又例如
df.add_suffix("_column")
output
A_column B_column
0 1 3
1 2 4
2 3 5
3 4 6

clip()方法

clip()方法主要是通过设置阈值来改变数据集当中的数值,当数值超过阈值的时候,就做出相应的调整
data = {'col_0': [9, -3, 0, -1, 5], 'col_1': [-2, -7, 6, 8, -5]}
df = pd.DataFrame(data)
output
df.clip(lower = -4, upper = 4)
output
col_0 col_1
0 4 -2
1 -3 -4
2 0 4
3 -1 4
4 4 -4
我们看到参数lower和upper分别代表阈值的上限与下限,数据集当中超过上限与下限的值会被替代。

filter()方法

pandas当中的filter()方法是用来筛选出特定范围的数据的,示例如下
df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12])),
index=['A', 'B', 'C', 'D'],
columns=['one', 'two', 'three'])
output
one two three
A 1 2 3
B 4 5 6
C 7 8 9
D 10 11 12
我们使用filter()方法来筛选数据
df.filter(items=['one', 'three'])
output
one three
A 1 3
B 4 6
C 7 9
D 10 12
我们还可以使用正则表达式来筛选数据
df.filter(regex='e$', axis=1)
output
one three
A 1 3
B 4 6
C 7 9
D 10 12
当然通过参数axis来调整筛选行方向或者是列方向的数据
df.filter(like='B', axis=0)
output
one two three
B 4 5 6

first()方法

当数据集当中的行索引是日期的时候,可以通过该方法来筛选前面几行的数据
index_1 = pd.date_range('2021-11-11', periods=5, freq='2D')
ts = pd.DataFrame({'A': [1, 2, 3, 4, 5]}, index=index_1)
ts
output
A
2021-11-11 1
2021-11-13 2
2021-11-15 3
2021-11-17 4
2021-11-19 5
我们使用first()方法来进行一些操作,例如筛选出前面3天的数据
ts.first('3D')
output
A
2021-11-11 1
2021-11-13 2

isin()方法

isin()方法主要是用来确认数据集当中的数值是否被包含在给定的列表当中
df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12])),
index=['A', 'B', 'C', 'D'],
columns=['one', 'two', 'three'])
df.isin([3, 5, 12])
output
one two three
A False False True
B False True False
C False False False
D False False True
若是数值被包含在列表当中了,也就是3、5、12当中,返回的是True,否则就返回False

df.plot.area()方法

如何在Pandas当中通过一行代码来绘制图表,将所有的列都通过面积图的方式来绘制
df = pd.DataFrame({
'sales': [30, 20, 38, 95, 106, 65],
'signups': [7, 9, 6, 12, 18, 13],
'visits': [20, 42, 28, 62, 81, 50],
}, index=pd.date_range(start='2021/01/01', end='2021/07/01', freq='M'))

ax = df.plot.area(figsize = (10, 5))
output

df.plot.bar()方法

下面我们看一下如何通过一行代码来绘制柱状图
df = pd.DataFrame({'label':['A', 'B', 'C', 'D'], 'values':[10, 30, 50, 70]})
ax = df.plot.bar(x='label', y='values', rot=20)
output

当然我们也可以根据不同的类别来绘制柱状图
age = [0.1, 17.5, 40, 48, 52, 69, 88]
weight = [2, 8, 70, 1.5, 25, 12, 28]
index = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
df = pd.DataFrame({'age': age, 'weight': weight}, index=index)
ax = df.plot.bar(rot=0)
output

当然我们也可以横向来绘制图表
ax = df.plot.barh(rot=0)
output

df.plot.box()方法

我们来看一下箱型图的具体的绘制,通过pandas一行代码来实现
data = np.random.randn(25, 3)
df = pd.DataFrame(data, columns=list('ABC'))
ax = df.plot.box()
output

df.plot.pie()方法

接下来是饼图的绘制
df = pd.DataFrame({'mass': [1.33, 4.87 , 5.97],
'radius': [2439.7, 6051.8, 6378.1]},
index=['Mercury', 'Venus', 'Earth'])
plot = df.plot.pie(y='mass', figsize=(8, 8))
output

除此之外,还有折线图、直方图、散点图等等,步骤与方式都与上述的技巧有异曲同工之妙,大家感兴趣的可以自己另外去尝试。

• concat()方法的简单介绍
• append()方法的简单介绍
• merge()方法的简单介绍
• join()方法的简单介绍
• 多重行索引的合并介绍
• 表格合并之后的列名重命名
• combine()方法的简单介绍
• combine_first()方法的简单介绍

Concat()方法的简单介绍

在我们开始concat()方法的正是介绍之前,我们先来看一下简单的例子
df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
"C": ["C0", "C1", "C2", "C3"],
"D": ["D0", "D1", "D2", "D3"],
},
index=[0, 1, 2, 3],
)
df2 = pd.DataFrame(
{
"A": ["A4", "A5", "A6", "A7"],
"B": ["B4", "B5", "B6", "B7"],
"C": ["C4", "C5", "C6", "C7"],
"D": ["D4", "D5", "D6", "D7"],
},
index=[4, 5, 6, 7],
)
df3 = pd.DataFrame(
{
"A": ["A8", "A9", "A10", "A11"],
"B": ["B8", "B9", "B10", "B11"],
"C": ["C8", "C9", "C10", "C11"],
"D": ["D8", "D9", "D10", "D11"],
},
index=[8, 9, 10, 11],
)
我们来看一下使用concat()方法之后的效果
frames = [df1, df2, df3]
result = pd.concat(frames)
result
output
A B C D
0 A0 B0 C0 D0
1 A1 B1 C1 D1
2 A2 B2 C2 D2
3 A3 B3 C3 D3
4 A4 B4 C4 D4
5 A5 B5 C5 D5
6 A6 B6 C6 D6
7 A7 B7 C7 D7
8 A8 B8 C8 D8
9 A9 B9 C9 D9
10 A10 B10 C10 D10
11 A11 B11 C11 D11
大致合并的方向就是按照轴垂直的方向来进行合并,如下图

下面小编来详细介绍一下concat()方法中的各个参数作用
pd.concat(
objs,
axis=0,
join="outer",
ignore_index=False,
keys=None,
levels=None,
names=None,
verify_integrity=False,
copy=True,
)
objs:需要用来进行合并的数据集,可以是Series类型或者是DataFrame类型的数据
axis:可以理解为是合并的方向,默认是0
join:可以理解为是合并的方式,有并集或是交集两种方式,默认的是并集
ignore_index:忽略索引,默认是False
keys:用于做行方向的多重索引
大家可能会有些迷惑,什么是多重的索引呢?看下面的例子
result = pd.concat(frames, keys=["x", "y", "z"])
result
output

如此一来,我们可以通过“x”、“y”以及“z”这些元素来获取每一部分的数据,例如
result.log["x"]
output
A B C D
0 A0 B0 C0 D0
1 A1 B1 C1 D1
2 A2 B2 C2 D2
3 A3 B3 C3 D3
除此之外,keys参数还能够被用在列索引上
s3 = pd.Series([0, 1, 2, 3], name="foo")
s4 = pd.Series([0, 1, 2, 3])
s5 = pd.Series([0, 1, 4, 5])
pd.concat([s3, s4, s5], axis=1, keys=["red", "blue", "yellow"])
output
red blue yellow
0 0 0 0
1 1 1 1
2 2 2 4
3 3 3 5
列名就变成了keys列表中的元素
而对于join参数,默认的是以outer也就是并集的方式在进行两表格的合并
df4 = pd.DataFrame(
{
"B": ["B2", "B3", "B6", "B7"],
"D": ["D2", "D3", "D6", "D7"],
"F": ["F2", "F3", "F6", "F7"],
},
index=[2, 3, 6, 7],
)
result = pd.concat([df1, df4], axis=1)
output

而当我们将join参数设置成inner,也就是交集的方式来进行合并,出来的结果就会不太一样
result = pd.concat([df1, df4], axis=1, join="inner")
output

接下来我们来看一下ignore_index参数的作用,它能够对行索引做一个重新的整合
result = pd.concat([df1, df4], ignore_index=True, sort=False)
output

对于一个表格是DataFrame格式,另外一个是Series格式,concat()方法也可以将两者合并起来,

s1 = pd.Series(["X0", "X1", "X2", "X3"], name="X")
result = pd.concat([df1, s1], axis=1)
output

要是在加上ignore_index参数的话,看一下效果会如何
result = pd.concat([df1, s1], axis=1, ignore_index=True)
output

append()方法的简单介绍

append()方法是对上面concat()方法的简单概括,我们来看一下简单的例子
result = df1.append(df2)
result
output

当然append()方法当中也可以放入多个DataFrame表格,代码如下
result = df1.append([df2, df3])
output

和上面的concat()方法相类似的是,append()方法中也有ignore_index参数,
result = df1.append(df4, ignore_index=True, sort=False)
output

同样地,我们也可以通过append()方法来给DataFrame表格添加几行的数据

s2 = pd.Series(["X0", "X1", "X2", "X3"], index=["A", "B", "C", "D"])
result = df1.append(s2, ignore_index=True)
output

关于Merge()方法的介绍

在merge()方法中有这些参数
pd.merge(
left,
right,
how="inner",
on=None,
left_on=None,
right_on=None,
left_index=False,
right_index=False,
sort=True,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
)
left/right:也就是所要合并的两个表格
on:左右所要合并的两表格的共同列名
left_on/right_on:两表格进行合并时所对应的字段
how:合并的方式,有left、right、outer、inner四种,默认是inner
suffixes:在两表格进行合并时,重复的列名后面添加的后缀
left_index:若为True,按照左表格的索引来连接两个数据集
right_index:若为True,按照右表格的索引来连接两个数据集
我们先来看一个简单的例子
left = pd.DataFrame(
{
"key": ["K0", "K1", "K2", "K3"],
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
}
)
right = pd.DataFrame(
{
"key": ["K0", "K1", "K2", "K3"],
"C": ["C0", "C1", "C2", "C3"],
"D": ["D0", "D1", "D2", "D3"],
}
)
result = pd.merge(left, right, on="key")
result
output

在merge()的过程当中有三种类型的合并,分别是一对一、多对一、多对多。其中“一对一”类型也就是merge()方法会去寻找两个表格当中相同的列,例如上面的“key”,并自动以这列作为键来进行排序,需要注意的是共同列中的元素其位置可以是不一致的。
那么来看一下“多对一”的合并类型,例如下面两张表格有共同的列“group”,并且第一张表格当中的“group”有两个相同的值,
df1:
employee group hire_date
0 Bob Accounting 2008
1 Jake Engineering 2002
2 Mike Engineering 2005
3 Linda HR 2010
df2:
group supervisor
0 Accounting Cathey
1 Engineering Dylan
2 HR James
然后我们来进行合并
pd.merge(df_1, df_2)
output
employee group hire_date supervisor
0 Bob Accounting 2008 Cathey
1 Jake Engineering 2002 Dylan
2 Mike Engineering 2005 Dylan
3 Linda HR 2010 James
最后便是“多对多”的合并类型,可以理解为两张表格的共同列中都存在着重复值,例如
df3:
employee group
0 Bob Accounting
1 Jake Engineering
2 Lisa Engineering
3 Sue HR
df4: group skills
0 Accounting math
1 Accounting spreadsheets
2 Engineering coding
3 Engineering linux
4 HR spreadsheets
5 HR organization
然后我们进行合并之后,看一下出来的结果
df = pd.merge(df3, df4)
print(df)
output
employee group skills
0 Bob Accounting math
1 Bob Accounting programming
2 Jake Engineering linux
3 Jake Engineering python
4 Lisa Engineering linux
5 Lisa Engineering python
6 Sue HR java
7 Sue HR c++
那么涉及到参数how有四种合并的方式,有“left”、“right”、“inner”、“outer”,分别代表
inner:也就是交集,在使用merge()方法的时候,默认采用的都是交集的合并方式
outer:可以理解为是并集的合并方式
left/right: 单方向的进行并集的合并
我们先来看一下“left”方向的并集的合并
result = pd.merge(left, right, how="left", on=["key1", "key2"])
result
output

我们再来看一下“right”方向的并集的合并
result = pd.merge(left, right, how="right", on=["key1", "key2"])
result
output

“outer”方式的合并
result = pd.merge(left, right, how="outer", on=["key1", "key2"])
result
output

“inner”方式的合并
result = pd.merge(left, right, how="inner", on=["key1", "key2"])
result
output

关于join()方法的简单介绍
join()方法用于将两个有着不同列索引的表格合并到一起,我们先来看一个简单的例子
left = pd.DataFrame(
{"A":["A0","A1","A2"],"B":["B0","B1","B2"]}, index=["K0", "K1", "K2"])
right = pd.DataFrame(
{"C": ["C0", "C2", "C3"], "D": ["D0", "D2", "D3"]}, index=["K0", "K2", "K3"]
)
result = left.join(right)
output

在join()方法中也有参数how用来定义合并的方式,和merge()方法相类似,这里便也有不做赘述
当多重行索引遇到join()方法
当遇到一表格,其中的行索引是多重行索引的时候,例如
left = pd.DataFrame(
{"A": ["A0", "A1", "A2"], "B": ["B0", "B1", "B2"]},
index=pd.Index(["K0", "K1", "K2"], name="key"),
)
index = pd.MultiIndex.from_tuples(
[("K0", "Y0"), ("K1", "Y1"), ("K2", "Y2"), ("K2", "Y3")],
names=["key", "Y"],
)
right = pd.DataFrame(
{"C": ["C0", "C1", "C2", "C3"], "D": ["D0", "D1", "D2", "D3"]},
index=index,
)
result = left.join(right, how="inner")
output

那么要是要合并的两张表格都是多重行索引呢?
leftindex = pd.MultiIndex.from_product(
[list("abc"), list("xy"), [1, 2]], names=["abc", "xy", "num"]
)
left = pd.DataFrame({"v1": range(12)}, index=leftindex)
output

        v1

abc xy num
a x 1 0
2 1
y 1 2
2 3
b x 1 4
2 5
y 1 6
2 7
c x 1 8
2 9
y 1 10
2 11
第二张表格如下
rightindex = pd.MultiIndex.from_product(
[list("abc"), list("xy")], names=["abc", "xy"]
)
right = pd.DataFrame({"v2": [100 * i for i in range(1, 7)]}, index=rightindex)
output
v2
abc xy
a x 100
y 200
b x 300
y 400
c x 500
y 600
将上述的两张表格进行合并
left.join(right, on=["abc", "xy"], how="inner")
output

        v1   v2

abc xy num
a x 1 0 100
2 1 100
y 1 2 200
2 3 200
b x 1 4 300
2 5 300
y 1 6 400
2 7 400
c x 1 8 500
2 9 500
y 1 10 600
2 11 600
列名的重命名
要是两张表格的列名相同,合并之后会对其列名进行重新命名,例如
left = pd.DataFrame({"k": ["K0", "K1", "K2"], "v": [1, 2, 3]})
right = pd.DataFrame({"k": ["K0", "K0", "K3"], "v": [4, 5, 6]})
result = pd.merge(left, right, on="k")
output

这里就不得不提到suffixes这个参数,通过这个参数来个列进行重命名,例如
result = pd.merge(left, right, on="k", suffixes=("_l", "_r"))
output

combine_first()方法的简单介绍

要是要合并的两表格,其中一个存在空值的情况,就可以使用combine_first()方法,
df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})
df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
df1.combine_first(df2)
output
A B
0 1.0 3.0
1 0.0 4.0
表格当中的空值就会被另外一张表格的非空值给替换掉
combine()方法的简单介绍
combine()方法是将两表格按照列的方向进行合并,但是不同在于还需要另外传进去一个第三方的函数或者是方法,来看一个简单的例子
df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
take_smaller = lambda s1, s2: s1 if s1.sum() < s2.sum() else s2
我们定义了一个简单的方法,在合并的过程中提取出总和较小的值
df1.combine(df2, take_smaller)
output
A B
0 0 3
1 0 3
要是表格中存在空值,combine()方法也有fill_value这个参数来处理
df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})
df2 = pd.DataFrame({'A': [2, 2], 'B': [3 3]})
df1.combine(df2, take_smaller, fill_value=-5)
output
A B
0 0 -5.0
1 0 4.0

标签:index,函数,PYTHON,DataFrame,df,pd,使用,output,方法
From: https://www.cnblogs.com/HeroZhang/p/17547437.html

相关文章

  • 函数
    函数定义与调用1先定义后调用2定义阶段不执行代码3调用函数才会执行代码(调用的时候一定要在函数名后加括号,若有参数,则传递参数)4函数名就相当于变量名指向的是内存中的函数代码所在的位置func()#报错name'func'isnotdefined#定义函数deffunc():print(......
  • PostgreSQL(pg) /MYSQL数据库,使用递归查询(WITH RECURSIVE)功能来实现获取指定菜单ID的
      PostgreSQL/MYSQL数据库,使用递归查询(WITHRECURSIVE)功能来实现获取指定菜单ID的所有下级菜单数据。下方用例是假设菜单表menu的改成自己的表即可WITHRECURSIVEmenu_hierarchyAS(SELECTid,name,parent_idFROMmenuWHEREid=<指......
  • 你信不信,只要学几天javascript就可以使用纯原生实现五星评分效果 【附完整代码】
    ......
  • Windows系统使用Nginx部署Vue
    Nginx是什么?Nginx(enginex)是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点开发的,因它的稳定性、丰富的功能集、简单的配置文件和低系统资源的消耗而闻名。优点速度更快、并发更高......
  • python实现两函数通过缩放,平移和旋转进行完美拟合
    Curve_fitting前几天在工作的时候接到了一个需求,希望将不同坐标系,不同角度的两条不规则曲线,并且组成该曲线的点集数量不一致,需求是希望那个可以通过算法的平移和旋转搞到一个概念里最贴合,拟合态进行比较。这是初步将两组数据画到图里的情况,和背景需求是一致的。其实从肉眼看过......
  • v3.3+使用 defineOptions 定义组件命名、版本、注册子组件
    在v3.3+版本中,可以使用defineOptions方法,定义组件命名、版本、注册子组件<scriptlang="ts"setup>import{Tabs,TabPane}from'ant-design-vue';import{ref}from'vue';import{achieveList}from'./data';importTabPackage......
  • python pip安装使用
    安装了python,没安装pip,在pycharm中执行pip命令会报错:py:无法将“py”项识别为cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。首先需要安装pip下载pip并解压到本地:https://pypi.org/project/pip/#files,window我下载......
  • Python 量化投资(一):滑动均值、布林带、MACD、RSI、KDJ、OBV
    滑动均值和标准差为了更好利用向量化来加速,滑动窗口使用np.lib.stride_tricks.sliding_window_view(x,win)提取,它会返回所有x[i]开头并且长度为win的数组的数组。defrolling(x,win):r=np.lib.stride_tricks.sliding_window_view(x,win)pad=np.zeros([len(x)-......
  • python魔术方法之__new__
    一、基本用法#从一个类建立一个对象#__new__从class建立一个object过程#__init__有了object初始化过程classLanguage:def__new__(cls,*args,**kwargs):print("__new__")returnsuper().__new__(cls)def__init__(self):print(......
  • VBA常用的文本函数 instr、mid
    InStr函数DimSearchString,SearchChar,MyPosSearchString="XXpXXpXXPXXP"'Stringtosearchin.SearchChar="P"'Searchfor"P".'Atextualcomparisonstartingatposition4.Returns6.MyPos=Inst......