如何在数据框列中附加值
how to append value in a dataframe column
我正试图了解我的发明随时间的演变,但我遇到了一个问题。当我尝试循环初始值 x 变化时,我得到一个完整的 NaN 列
这是代码
value = 1000
total = []
for variation in df["Variation"]:
value = value * variation
total.append(value)
我已经尝试过相同的算法并成功了
list=[1,2,3,4,5]
a = 2
results = []
for x in list:
a = a * x
results.append(a)
哪里错了?
应该这样做
for variation in df["Variation"].tolist():
value = value * variation
total.append(value)
不是循环,更像 pandas 的方法是 cumprod()
:
df = pd.DataFrame({'Variation': [1, 2, 3, 4, 5]})
value = 2
total = df.Variation.cumprod() * value
# 0 2
# 1 4
# 2 12
# 3 48
# 4 240
# Name: Variation, dtype: int64
根据 nan
评论,请注意 cumprod()
也可以无缝处理 nan
:
df = pd.DataFrame({'Variation': [np.nan, 2, 3, 4, 5]})
value = 2
total = df.Variation.cumprod() * value
# 0 NaN
# 1 4.0
# 2 12.0
# 3 48.0
# 4 240.0
# Name: Variation, dtype: float64
我正试图了解我的发明随时间的演变,但我遇到了一个问题。当我尝试循环初始值 x 变化时,我得到一个完整的 NaN 列
这是代码
value = 1000
total = []
for variation in df["Variation"]:
value = value * variation
total.append(value)
我已经尝试过相同的算法并成功了
list=[1,2,3,4,5]
a = 2
results = []
for x in list:
a = a * x
results.append(a)
哪里错了?
应该这样做
for variation in df["Variation"].tolist():
value = value * variation
total.append(value)
不是循环,更像 pandas 的方法是 cumprod()
:
df = pd.DataFrame({'Variation': [1, 2, 3, 4, 5]})
value = 2
total = df.Variation.cumprod() * value
# 0 2
# 1 4
# 2 12
# 3 48
# 4 240
# Name: Variation, dtype: int64
根据 nan
评论,请注意 cumprod()
也可以无缝处理 nan
:
df = pd.DataFrame({'Variation': [np.nan, 2, 3, 4, 5]})
value = 2
total = df.Variation.cumprod() * value
# 0 NaN
# 1 4.0
# 2 12.0
# 3 48.0
# 4 240.0
# Name: Variation, dtype: float64