Python Pandas dataframe.reindex_like()

Python Pandas dataframe.reindex_like()

Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据变得更加容易。

Pandas dataframe.reindex_like()函数返回一个与自己索引匹配的对象。任何不匹配的索引都会被填充为NaN值。

语法:
语法 : DataFrame.reindex_like(other, method=None, copy=True, limit=None, tolerance=None)

参数 :
other:对象
method:字符串或无
copy : 布尔值,默认为True
limit :为不精确的匹配填写的最大连续标签数。
tolerance :其他对象的标签和这个对象的标签之间的最大距离,用于不精确的匹配。可以是列表式的。

返回:重新索引:与输入相同

示例#1:使用reindex_like()函数在给定的两个数据帧之间找到匹配的索引。

注意:我们可以通过使用任何一种填充方法(例如,’fill’,’bfill’)来填补缺失的数值。

# importing pandas as pd
import pandas as pd
  
# Creating the first dataframe 
df1 = pd.DataFrame({"A":[1, 5, 3, 4, 2],
                    "B":[3, 2, 4, 3, 4],
                    "C":[2, 2, 7, 3, 4],
                    "D":[4, 3, 6, 12, 7]},
                    index =["A1", "A2", "A3", "A4", "A5"])
  
# Creating the second dataframe
df2 = pd.DataFrame({"A":[10, 11, 7, 8, 5], 
                    "B":[21, 5, 32, 4, 6],
                    "C":[11, 21, 23, 7, 9], 
                    "D":[1, 5, 3, 8, 6]}, 
                     index =["A1", "A3", "A4", "A7", "A8"])
  
# Print the first dataframe
df1
  
# Print the second dataframe
df2

Python Pandas dataframe.reindex_like()
Python Pandas dataframe.reindex_like()

让我们使用dataframe.reindex_like()函数来找到匹配的索引。

# find matching indexes
df1.reindex_like(df2)

输出 :
Python Pandas dataframe.reindex_like()

注意输出结果,未匹配的索引被填充为NaN值,我们可以使用’fill’方法填补缺失的值。

# filling the missing values using ffill method
df1.reindex_like(df2, method ='ffill')

输出 :
Python Pandas dataframe.reindex_like()
注意在输出中,新的索引已经使用 “A5 “行被填充。

示例#2:使用reindex_like()函数来匹配两个数据框的索引,并限制填充缺失的值。

# importing pandas as pd
import pandas as pd
  
# Creating the first dataframe 
df1 = pd.DataFrame({"A":[1, 5, 3, 4, 2],
                    "B":[3, 2, 4, 3, 4],
                    "C":[2, 2, 7, 3, 4],
                    "D":[4, 3, 6, 12, 7]},
                    index =["A1", "A2", "A3", "A4", "A5"])
  
# Creating the second dataframe
df2 = pd.DataFrame({"A":[10, 11, 7, 8, 5],
                    "B":[21, 5, 32, 4, 6],
                    "F":[11, 21, 23, 7, 9],
                    "K":[1, 5, 3, 8, 6]},
                    index =["A1", "A2", "A3", "A4", "A7"])
  
# matching the indexes
df1.reindex_like(df2)

输出 :
Python Pandas dataframe.reindex_like()
注意输出结果,未匹配的索引被填充为NaN值,我们可以使用’fill’方法填充缺失的值。我们还使用limit参数限制可以被填充的连续未匹配索引的数量。

# match the indexes
# fill the unmatched index using 'ffill' method
# maximum consecutive unmatched indexes to be filled is 1
  
df.reindex_like(df1, method ='ffill', limit = 1)

输出 :
Python Pandas dataframe.reindex_like()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程