【发布时间】:2022-01-10 10:21:27
【问题描述】:
我在 Stackoverflow 上找到了这个问题的答案:Calculate MRR in Python Pandas dataframe
但是当我尝试用我的数据框实现它时,它会返回一个错误,详细信息:
startdate amount months
0 2021-11-03 10:32:31 166.0 12
1 2021-11-03 10:02:37 155.0 5
代码如下:
df.resample('M').sum()
dfs = []
for date, values in df.iterrows():
months, price = values
dfs.append(
pd.DataFrame(
# Compute the price for each month, and repeat this value
data={'price': [price / months] * months},
# The index is a date range for the requested number of months
index=pd.date_range(date, periods=months, freq='M')
)
)
错误信息:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-116-89e50648a780> in <module>
1 dfs = []
2 for date, values in df.iterrows():
----> 3 months, price = values
4 dfs.append(
5 pd.DataFrame(
ValueError: too many values to unpack (expected 2)
我尝试更改变量等,但找不到解决错误的方法。 我正在处理 1000 多行数据。
【问题讨论】:
-
months, price = values[["months", "amount"]]因为 values 是一个带有列名的字典。编辑:双方括号 -
请注意,
df.resample('M').sum()行不会产生任何结果,因为您没有将其分配给任何东西。它可以被忽略,您的代码结果不会改变。 -
另外,你为什么要除以月份再乘以 - 我错过了什么吗?
-
@LarrytheLlama 从技术上讲,
values是 Pandas 行。 -
您是否打算在新数据框中实际制作
months长度列表?因为这就是[price / months] * months所做的。
标签: python pandas dataframe datetime