📜  Python| Pandas DataFrame.truediv(1)

📅  最后修改于: 2023-12-03 15:19:15.243000             🧑  作者: Mango

Python | Pandas DataFrame.truediv

The truediv() function in Pandas DataFrame is used to perform floating point division operation on the values of DataFrame. It is an element-wise operator and is equivalent to / operator.

Syntax:
DataFrame.truediv(other, level=None, fill_value=None, axis=None)
Parameters:
  • other: DataFrame, Series or scalar value to divide the calling DataFrame with.
  • level: It is used for broadcasting along a particular level, matching Index values on the passed MultiIndex level.
  • fill_value: Value to be replaced with NaN values of the DataFrame before the operation is performed. It is None by default.
  • axis: Axis to be divided over. It is 0 by default.
Returns:

A DataFrame with the result of division of the original DataFrame with the passed argument.

Let's see some examples to understand this function better.

Example 1:
import pandas as pd
df1 = pd.DataFrame({'a': [10, 20, 30], 'b': [20, 30, 40]})
df2 = pd.DataFrame({'a': [5, 4, 3], 'b': [2, 3, 4]})
result = df1.truediv(df2)
print(result)

Output:

     a         b
0  2.0  10.000000
1  5.0  10.000000
2 10.0  10.000000

In the above example, we have two dataframes df1 and df2. We have divided df1 with df2 element-wise using the truediv() function.

Example 2:
import pandas as pd
df = pd.DataFrame({'a': [10, 20, 30], 'b': [20, 30, 40]})
result = df.truediv(10)
print(result)

Output:

     a    b
0  1.0  2.0
1  2.0  3.0
2  3.0  4.0

In the above example, we have a dataframe df. We are dividing the values of the dataframe with a scalar value of 10.

Note: The division operator / can also be used instead of truediv() to perform element-wise floating point division.