import numpy as np
import pandas as pd
# 乘法 # mul 仍然是np.nan
print(
pd.Series([1, 2]).mul(pd.Series([np.nan]))
)
在 Pandas 中,你可以对 Series 进行各种数学运算,包括加法、减法、乘法和除法。让我们来看一下如何在 Pandas 中执行 Series 的乘法操作。
首先,我们假设你有一个 DataFrame 和一个 Series,它们的结构如下:
import numpy as np
import pandas as pd
# 创建一个 DataFrame
frame = pd.DataFrame(np.arange(9).reshape(3, 3), columns=['a', 'b', 'c'], index=['one', 'two', 'threee'])
# 创建一个 Series
series = frame['b']
DataFrame frame
的内容如下:
a | b | c | |
one | 0 | 1 | 2 |
two | 3 | 4 | 5 |
threee | 6 | 7 | 8 |
Series series
的内容如下:
b | |
one | 1 |
two | 4 |
threee | 7 |
接下来,我们可以执行以下运算:
- 加法:
frame.add(series, axis=0)
- 结果如下:
a | b | c | |
one | 1 | 2 | 3 |
two | 7 | 8 | 9 |
threee | 13 | 14 | 15 |
- 减法:
frame.sub(series, axis=0)
- 结果如下:
a | b | c | |
one | -1 | 0 | 1 |
two | -1 | 0 | 1 |
threee | -1 | 0 | 1 |
- 乘法:
frame.mul(series, axis=0)
- 结果如下:
a | b | c | |
one | 0 | 1 | 2 |
two | 12 | 16 | 20 |
threee | 42 | 49 | 56 |
- 除法:
frame.div(series, axis=0)
- 结果如下:
a | b | c | |
one | 0.000000 | 1.0 | 2.000000 |
two | 0.750000 | 1.0 | 1.250000 |
threee | 0.857143 | 1.0 | 1.142857 |
请注意,如果你在运算中犯了以下错误,会导致不正确的结果:
- 错误的轴:
frame.add(series, axis=1)
或使用+
、-
、*
、/
符号进行运算。 - 不能直接使用
+
、-
、*
、/
符号进行运算。
希望这些示例对你理解 Pandas Series 的数学运算有所