Python|熊猫 dataframe.div()
Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。
Pandas dataframe.div()用于查找数据帧和其他元素的浮动划分。此函数类似于 dataframe/other,但额外支持处理其中一个输入数据中的缺失值。
Syntax: DataFrame.div(other, axis=’columns’, level=None, fill_value=None)
Parameters:
other : Series, DataFrame, or constant
axis : For Series input, axis to match Series index on
fill_value : Fill missing (NaN) values with this value. If both DataFrame locations are missing, the result will be missing
level : Broadcast across a level, matching Index values on the passed MultiIndex level
Returns: result : DataFrame
示例 #1:使用 div()函数查找具有常数值的数据框元素的浮动除法。还要处理数据框中存在的 NaN 值。
Python3
# importing pandas as pd
import pandas as pd
# Creating the dataframe with NaN value
df = pd.DataFrame({"A":[5, 3, None, 4],
"B":[None, 2, 4, 3],
"C":[4, 3, 8, 5],
"D":[5, 4, 2, None]})
# Print the dataframe
df
Python3
# Find the division with 50 being substituted
# for all the missing values in the dataframe
df.div(2, fill_value = 50)
Python3
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[5, 3, 6, 4],
"B":[11, 2, 4, 3],
"C":[4, 3, 8, 5],
"D":[5, 4, 2, 8]})
# Create a series object with no. of elements
# equal to the element along the index axis.
# Creating a pandas series object
series_object = pd.Series([2, 3, 1.5, 4])
# Print the series_obejct
series_object
Python3
# To find the division
df.div(series_object, axis = 0)
现在找到每个数据框元素与 2 的除法
Python3
# Find the division with 50 being substituted
# for all the missing values in the dataframe
df.div(2, fill_value = 50)
输出 :
输出是一个数据框,其中包含每个单元格值除以 2 的结果的单元格。在执行除法之前,所有 NaN 单元格都已填充 50。示例 #2:使用 div()函数在索引轴上查找具有系列对象的数据帧的浮动分割。
Python3
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[5, 3, 6, 4],
"B":[11, 2, 4, 3],
"C":[4, 3, 8, 5],
"D":[5, 4, 2, 8]})
# Create a series object with no. of elements
# equal to the element along the index axis.
# Creating a pandas series object
series_object = pd.Series([2, 3, 1.5, 4])
# Print the series_obejct
series_object
输出 :
注意:如果dataframe的索引轴的维度和series对象的维度不一样会报错。
现在,沿着索引轴找到数据框元素与系列对象的划分
Python3
# To find the division
df.div(series_object, axis = 0)
输出 :
输出是一个数据框,其中的单元格包含当前单元格元素与相应系列对象单元格的划分结果。