Python | Pandas DataFrame.truediv

Python Methods and Functions

DataFrame.truediv() Pandas DataFrame.truediv() executes DataFrame .truediv () dividing data and other elements element by element. This is equivalent to dataframe / other , but with support for fill_value replacement for missing data in one of the inputs.

Syntax: DataFrame.truediv ( other, axis = 'columns', level = None, fill_value = None)

Parameter:
other: scalar, sequence, Series , or DataFrame
axis: {0 or 'index', 1 or 'columns'}
level: Broadcast across a level, matching Index values on the passed MultiIndex level.
fill_value: Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment.

Returns: Result of the arithmetic operation.

Example # 1: Use DataFrame.truediv () to divide a given dataframe with scalar elementwise. Also fill in 100 for any missing values.

# import pandas as pd

import pandas as pd

 
# Create DataFrame

df = pd.DataFrame ({ "A" : [ 12 , 4 , 5 , None , 1 ], 

"B " : [ 7 , 2 , 54 , 3 , None ], 

"C" : [ 20 , 16 , 11 , 3 , 8 ], 

"D" : [ 14 , 3 , None , 2 , 6 ]}) 

 
# Create index

index_ = [ 'Row_1' , ' Row_2' , 'Row_3' , ' Row_4' , 'Row_5' ]

 
# Set index

df.index = index_

  
# Print DataFrame

print (df)

Output:

We will now use DataFrame.truediv () to divide this dataframe by 2 element by element. We're going to fill 100 in place of all missing values ​​in this data frame.

# divide by 2 elements
# fill in 100 for missing values ​​

result = df.truediv (other = 2 , fill_value = 100 )

 
# Print result

print (result)

Output:

As we can see on you In progress, DataFrame.truediv () has successfully divided the given dataframe by a scalar.

Example # 2: Use DataFrame.truediv () to split this dataframe using a list.

# import pandas as pd

import pandas as pd

 
# Create DataFrame

df = pd.DataFrame ({ "A" : [ 12 , 4 , 5 , None , 1 ], 

" B " : [ 7 , 2 , 54 , 3 , None ] , 

"C" : [ 20 , 16 , 11 , 3 , 8 ], 

  "D" : [ 14 3 , None , 2 , 6 ]}) 

  
# Create index

index_ = [ ' Row_1' , 'Row_2' , 'Row_3' , ' Row_4' , ' Row_5' ]

  
# Set index

df.index = index_

  
# Print DataFrame

print (df)

Exit :

Now we will use DataFrame.truediv () to split this information frame using a list.

# split using list
# along the column axis

result = df.truediv (other = [ 10 , 4 , 8 , 3 ], axis = 1 )

 
# Print result

print (result)

Output:

As we can see in the output, DataFrame.truediv () did the division successfully the specified data frame to the list.