I have a function which updates a dataframe that I have passed in:
def update_df(df, x, i):
for i in range(x):
list = ['name' str(i), i 2, i - 1]
df.loc[i] = list
return df, i
df = pd.DataFrame(columns=['lib', 'qty1', 'qty2'])
i = 0
df, i = update_df(df, 6, i)
What I would like to do, is be able to modify the dataframe after running it through the update_df(df, x, i)
function I created but I am not having much luck with it. The following is an example of what I am trying to do I am just trying to is concatenate the values of the last two rows in the lib
column together:
temp = df.loc[i][0] df.loc[i-1][0]
print(temp)
df.loc[i][0] = temp
print(df)
The following is the output I get:
name5name4
lib qty1 qty2
0 name0 2 -1
1 name1 3 0
2 name2 4 1
3 name3 5 2
4 name4 6 3
5 name5 7 4
But what I hope to get is:
name5name4
lib qty1 qty2
0 name0 2 -1
1 name1 3 0
2 name2 4 1
3 name3 5 2
4 name4 6 3
5 name5name4 7 4
This is part of a larger project where I will be constantly writing to a dataframe and then eventually write the dataframe to a file. Periodically I will want to update the last row of the dataframe which is where I am looking to figure out how to update it appropriately. I would like to avoid making a copy of the dataframe and just stick with one that I update throughout my code.
CodePudding user response:
If all you want is to concatenate the last two values in the lib
column, and reassign the last row's lib
column to that value:
df.loc[df.index[-1], "lib"] = df[-2:]["lib"].sum()