1 year ago
#311009
orkedahmad
How to fix Error Data must be 1-dimensional
Let's say I have this set of dataframe.
import pandas as pd
data = [['30-06-2021', 3.4, 43578, '31-01-2022', 5000, '28-02-2022', 78564, '31-03-2022', 52353, '30-04-2022'],
['14-06-2021', 8.9, 4475, '14-01-2022', 2546, '05-02-2022', 5757, '28-03-2022', 2352, '01-04-2022']]
ds = pd.DataFrame(data, columns = ['Start', 'Rate', 'Jan-22Total', 'Jan-22', 'Feb-22Total', 'Feb-22', 'Mar-22Total', 'Mar-22',
'Apr-22Total', 'Apr-22'])
And I want to add 1 more column as Overall Total
to calculate this formula Jan-22Total^(1(1+Rate)^((Jan-22-Start)/365)+Feb-22Total^(1(1+Rate)^((Feb-22-Start)/365)+Mar-22Total^(1(1+Rate)^((Mar-22-Start)/365)+ ... and so on as I have the repeated monthly column.
How could possibly I did this in a shorter way?
Here's is what I have done so far
m = pd.to_datetime(ds.columns.str.extract(r'([A-Z][a-z]{2}-\d+\Z)', expand=False), format='%b-%y', errors='coerce').notna()
cols = ds.columns[m]
start = pd.to_datetime(ds['Start'], dayfirst=True)
dates = ds[cols].apply(pd.to_datetime, dayfirst=True)
years = dates.sub(start, axis=0).astype('timedelta64[D]').div(365)
rate = ds['Rate'] / 100
rate2 = 1 + rate
rate3 = rate2.pow(years.values)
rate4 = 1 / rate3
ds['Overall Total'] = ds[cols + 'Total'].pow(rate4.values).sum(1)
However, I got an error in the rate
line saying that ValueError: Data must be 1-dimensional.
Is there any idea how to fix this code?
python
dataframe
dimension
0 Answers
Your Answer