将Python Dataframe列与固定变量相乘

时间:2019-09-01 04:48:49

标签: python python-3.x

我可以用常数减去Dataframe列。示例:

snp_sum = snp['Adj Close'] - 10

但是,一旦我用变量snp_30Y替换常量,它就不起作用了:

snp_30Y = ((snp_t1-snp_t0)/snp_t0)
snp_30Y = snp_30Y.values 
snp_sum = snp['Adj Close'] - snp_30Y

我得到的结果是ValueError: Length of passed values is 1, index implies 360

结果应该与我将变量定义为像10这样的常数一样。

snp_sum = snp['Adj Close'] - 10

结果:

0       267.720001
1       287.470001
2       278.859985
3       284.869995
4       299.640015

1 个答案:

答案 0 :(得分:0)

正如wjandrea所指出的,您的示例不是reproducible。另外,标题与示例不匹配:在示例显示一些减法的同时,您提到了乘法。

所以这是一些一般性的答案,但是如果您想获得更具体的问题,请更新您的问题。

可以对两个数据框列(相乘,相减等)进行操作,但前提是它们的维数相同。您可以使用<col>.shapelen(<col>)检查该尺寸。

还请注意,在熊猫中,您应该了解几种类型:完整的数据帧是Dataframe,而单列是Series。这些对象是名为numpy的更底层和更有效的array对象的包装。您可以使用<col_or_df>.values访问这些较低级别的对象。支持SeriesSeries之间以及Seriesarray之间的操作。这就是为什么您有两种执行要求的方法的原因:

import pandas as pd

# data
df = pd.DataFrame({'a': [0, 10, 20],
                   'b': [1, 11, 21]})

# subtracting a constant
df_cst = df['a'] - 1
print("df_cst (type subtracted: %s)" % type(1))
print(df_cst)
print()

# subtracting a column (= a Series)
df_var = df['a'] - df['b']
print("df_var (type subtracted: %s)" % type(df['b']))
print(df_var)
print()

# subtracting a column values (= a numpy array)
df_var2 = df['a'] - df['b'].values
print("df_var2 (type subtracted: %s)" % type(df['b'].values))
print(df_var2)

收益

df_cst (type subtracted: <class 'int'>)
0    -1
1     9
2    19
Name: a, dtype: int64

df_var (type subtracted: <class 'pandas.core.series.Series'>)
0   -1
1   -1
2   -1
dtype: int64

df_var2 (type subtracted: <class 'numpy.ndarray'>)
0   -1
1   -1
2   -1
Name: a, dtype: int64

如您所见,当减法中的两个变量中只有一个是数据帧列(Series)时,结果将沿用其名称。当第二项也是Series时,名称便会丢失,因为熊猫无法知道要使用哪个名称作为结果。