Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

python - Loop: Results to be updated via += if on the same date, otherwise write next line

I have a function that produces some output like this

date         cashflow       count   etc
1/1/2000        40            3       ...

always a one-liner. This is created many times, with same or different dates. Now I would like a record of all results

date      cashflow         count    etc
1/1/2000     40              3      ...

so if a new result comes in with the same date / index, than it should add and update the field, i.e. via "+=", however if its a different date that does not already exists in the table, than it should just append and provide basis for further "updates", i.e.

new result

date      cashflow         count    etc
1/1/2000     -20              1      ...

then my table should show

date      cashflow         count    etc
1/1/2000     20              4      ...

however if a new results hits in with a date not yet existing in the table

date      cashflow         count    etc
2/1/2000     10              20     ...

then my table would look like

date      cashflow         count    etc
1/1/2000     20              4      ...
2/1/2000     10              20     ...

edit1: It seems my question did not come out clear: How would a program look like that could:

1) if index coincide: update values +=

2) if index not does not exist, extend the table by that line

edit2: How would I need to change the below code, if my date was set as an index?

edit3: Somehow this doesn't work within a loop: In a simple setup each of these one-liners are pd.DataFrames. However, in a loop they seem to be something else, such that I get the error:

AttributeError: 'NoneType' object has no attribute 'groupby'

If I leave aout the groupbyand use only sum:

AttributeError: 'NoneType' object has no attribute 'sum'

I think the loop is creating some kind of list of data frames; appending only works though.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use DataFrame.append and then group by the column you want to use as an index.

Let's say that total_df is the table to which you want to add new rows, new_df is the table containing those new rows and date is the column to be used as index. Then you can use:

total_df.append(new_df).groupby(by='date').sum()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...