Python Pandas dataframe.add()

Python Pandas dataframe.add()

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

Dataframe.add()方法用于对dataframe和其他的元素进行添加(二进制运算符添加)。相当于dataframe + other,但支持用fill_value来替代其中一个输入的缺失数据。

语法: DataFrame.add(other, axis=’columns’, level=None, fill_value=None)

参数:

other:系列,数据框架,或常数
axis: {0, 1, ‘index’, ‘columns’}对于系列输入,axis要与系列的索引相匹配。
fill_value : [None or float value, default None] 用这个值填充缺失的(NaN)值。如果两个DataFrame的位置都缺失,结果将是缺失。
level : [int or name] 在一个级别上进行广播,与通过的MultiIndex级别上的索引值相匹配。

返回:结果数据框架

# Importing Pandas as pd
import pandas as pd
  
# Importing numpy as np
import numpy as np
  
# Creating a dataframe
# Setting the seed value to re-generate the result.
np.random.seed(25)
  
df = pd.DataFrame(np.random.rand(10, 3), columns =['A', 'B', 'C'])
  
# np.random.rand(10, 3) has generated a
# random 2-Dimensional array of shape 10 * 3
# which is then converted to a dataframe
  
df

Python Pandas dataframe.add()

注意: add()函数类似于’+’操作,但是,add()对其中一个输入的缺失值提供额外的支持。

# We want NaN values in dataframe. 
# so let's fill the last row with NaN value
df.iloc[-1] = np.nan
  
df

Python Pandas dataframe.add()

使用add()函数将一个常量值添加到数据框中:

# add 1 to all the elements
# of the data frame
df.add(1)
  

Python Pandas dataframe.add()

注意上面的输出,在df数据框架中的nan单元格没有发生加法,add()函数有一个属性fill_value。这将用指定的值来填补缺失的值(Nan)。如果两个数据框架的值都缺失,那么,结果将是缺失。

让我们看看如何做到这一点。

# We have given a default value
# of '10' for all the nan cells
df.add(1, fill_value = 10)

Python Pandas dataframe.add()
所有的纳米单元格都先填上了10,然后再加上1。

向数据框架添加系列:

对于系列输入,数据框架和系列的索引尺寸必须匹配。

# Create a Series of 10 values
tk = pd.Series(np.ones(10))
  
# tk is a Series of 10 elements
# all filled with 1

Python Pandas dataframe.add()

# Add tk(series) to the df(dataframe)
# along the index axis
df.add(tk, axis ='index')

Python Pandas dataframe.add()

将一个数据框架与其他数据框架相加

# Create a second dataframe
# First set the seed to regenerate the result
np.random.seed(10)
  
# Create a 5 * 5 dataframe
df2 = pd.DataFrame(np.random.rand(5, 5), columns =['A', 'B', 'C', 'D', 'E'])
  
df2

Python Pandas dataframe.add()

让我们对这两个数据框进行元素相加

df.add(df2)

Python Pandas dataframe.add()

请注意,所产生的数据框架的尺寸为10*5,并且在所有那些数据框架的单元格中都有纳值。

让我们来解决这个问题 –

# Set a default value of 10 for nan cells
# nan value won't be filled for those cells
# in which both data frames has nan value
df.add(df2, fill_value = 10)

Python Pandas dataframe.add()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程