将Python Dataframe列与固定变量相乘

将Python Dataframe列与固定变量相乘,python,python-3.x,Python,Python 3.x,我可以用常量减去数据帧列。例如: 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:传递值的长度是1,索引意味着360 结果应该与我将变量定义为10这样的常量一样 snp_sum = sn

我可以用常量减去数据帧列。例如:

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:传递值的长度是1,索引意味着360

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

snp_sum = snp['Adj Close'] - 10
结果:

0       267.720001
1       287.470001
2       278.859985
3       284.869995
4       299.640015
正如所指出的,你的例子并非如此。此外,标题与示例不匹配:您提到了乘法,而示例显示了一些减法

这里有一些一般性的答案,但如果你想得到更具体的答案,请更新你的问题

可以对两个数据帧列(相乘、相减等)进行操作,但前提是它们具有相同的维度。您可以使用
.shape
len()
检查该尺寸

另外请注意,在pandas中,有几种类型您应该知道:完整的数据帧是
数据帧
,而单个列是
系列
。这些对象是名为
array
的更低级、更高效的
numpy
对象的包装。您可以使用
.values
访问这些低级对象。支持
系列
系列
之间的操作,以及
系列
阵列
之间的操作。这就是为什么你有两种方法来实现你的要求:

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
df_cst(类型减去:)
0    -1
1     9
2    19
名称:a,数据类型:int64
df_变量(类型减去:)
0   -1
1   -1
2   -1
数据类型:int64
df_var2(类型减去:)
0   -1
1   -1
2   -1
名称:a,数据类型:int64

正如您所看到的,当减法中的两个变量中只有一个是数据帧列(a
系列
)时,结果会带有其名称。当第二项也是一个
系列时,
,名字就丢失了,因为熊猫没有办法知道用哪个名字来表示结果。

那么
snp\u sum=snp['Adj Close']-snp\u 30Y[0]
?什么是
snp\u t1
snp\u t0
?你需要澄清这个问题。阅读更多细节。