Pandas DataFrame.mod(~) 方法计算源 DataFrame 和另一个标量、序列、Series 或 DataFrame 中的值的模,即:
DataFrame % other
注意
除非您使用参数 axis 、 level 和 fill_value ,否则 mod(~) 相当于使用 % 运算符计算模数。
参数
1.other | scalar 或 sequence 或 Series 或 DataFrame
生成的 DataFrame 将是源 DataFrame 和 other 的模。
2. axis | int 或 string | optional
是否为源DataFrame的每一列或每一行广播other:
|
轴 |
说明 |
|---|---|
|
|
每列广播 |
|
|
每行广播 |
仅当源 DataFrame 的形状与 other 的形状不对齐时,这才相关。默认情况下,axis=1 。
3. level | int 或 string | optional
要考虑的级别的名称或整数索引。仅当您的 DataFrame 是多索引时,这才相关。
4. fill_value | float 或 None | optional
在计算模数之前替换 NaN 的值。如果源 DataFrame 和另一个中的条目均为 NaN ,则该条目的结果仍为 NaN 。默认情况下,fill_value=None 。
返回值
通过源 DataFrame 和 other 的模计算出的新 DataFrame 。
例子
基本用法
考虑以下数据帧:
df = pd.DataFrame({"A":[12,13], "B":[24,25]})
df_other = pd.DataFrame({"A":[4,5], "B":[7,8]})
A B | A B
0 12 24 | 0 4 7
1 13 25 | 1 5 8
计算模:
df.mod(df_other)
A B
0 0 3
1 3 1
请注意,这相当于:
df % df_other
A B
0 0 3
1 3 1
广播
考虑以下 DataFrame :
df = pd.DataFrame({"A":[12,13], "B":[24,25]})
df
A B
0 12 24
1 13 25
逐行加法
默认情况下, axis=1 ,这意味着 other 将为 df 中的每一行广播:
df.mod([10,20]) # axis=1
A B
0 2 4
1 3 5
在这里,我们计算以下逐元素模:
12%10 24%20
13%10 25%20
逐列加法
要为 df 中的每一列广播 other,请像这样设置 axis=0:
df.mod([10,20], axis=0)
A B
0 2 4
1 13 5
在这里,我们计算以下逐元素模:
12%10 24%10
13%20 25%20
指定fill_value
考虑以下数据帧:
df = pd.DataFrame({"A":[12,np.NaN], "B":[np.NaN,25]})
df_other = pd.DataFrame({"A":[10,20],"B":[np.NaN,np.NaN]})
A B | A B
0 12.0 NaN | 0 10 NaN
1 NaN 25.0 | 1 20 NaN
默认情况下,当我们使用 mod(~) 计算模数时,任何使用 NaN 的操作都会产生 NaN :
df.mod(df_other)
A B
0 2.0 NaN
1 NaN NaN
在使用 fill_value 参数计算模数之前,我们可以填充 NaN 值:
df.mod(df_other, fill_value=5)
A B
0 2.0 NaN
1 5.0 0.0
请注意,无论 fill_value 如何,两个 NaN 之间的运算仍然会产生 NaN 。
相关用法
- Python Pandas DataFrame mode方法用法及代码示例
- Python Pandas DataFrame max方法用法及代码示例
- Python Pandas DataFrame mean方法用法及代码示例
- Python Pandas DataFrame memory_usage方法用法及代码示例
- Python Pandas DataFrame merge方法用法及代码示例
- Python Pandas DataFrame melt方法用法及代码示例
- Python Pandas DataFrame median方法用法及代码示例
- Python Pandas DataFrame mask方法用法及代码示例
- Python Pandas DataFrame min方法用法及代码示例
- Python Pandas DataFrame mad方法用法及代码示例
- Python Pandas DataFrame mul方法用法及代码示例
- Python Pandas DataFrame empty属性用法及代码示例
- Python Pandas DataFrame pop方法用法及代码示例
- Python Pandas DataFrame nsmallest方法用法及代码示例
- Python Pandas DataFrame sample方法用法及代码示例
- Python Pandas DataFrame items方法用法及代码示例
- Python Pandas DataFrame swaplevel方法用法及代码示例
- Python Pandas DataFrame agg方法用法及代码示例
- Python Pandas DataFrame copy方法用法及代码示例
- Python Pandas DataFrame pow方法用法及代码示例
- Python Pandas DataFrame insert方法用法及代码示例
- Python Pandas DataFrame lt方法用法及代码示例
- Python Pandas DataFrame all方法用法及代码示例
- Python Pandas DataFrame unstack方法用法及代码示例
- Python PySpark DataFrame filter方法用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Pandas DataFrame | mod method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
