简体   繁体   中英

Pandas not appending values to data frame

I have a file called balance.csv. It contains user data such as their discord ID number, their account balance, and the amount of stocks that they own. I'm trying to create a simple command using discord.py that lets them know their account balance. If they don't have an account, it initializes one for them. However, the values aren't being appended to the CSV file when the code tries to initialize the account. I am not sure where the problem is and why it is occurring. I'm using pandas and discord.py.

balance_data = pd.read_csv('balance.csv')

def init_account(id):
    global balance_data
    balance_data = balance_data.append({"user_id":id, "account_balance":100, "stocks":0}, ignore_index=True)

@client.command(name='bal')
async def balance(ctx):
    if ctx.author.id not in balance_data["user_id"].values:
        await ctx.send("Creating Account...")
        init_account(ctx.author.id)
        await ctx.send("Account created.")
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
    else:
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")

The dataframe and the CSV file are two separate things. Just because you read the dataframe from a file doesn't mean that modifying the dataframe will modify the file. It does not create any kind of persistent "sync" between the dataframe and the file. If you want to change the file, you need to use .to_csv to write back out to the file.

Read data frame with read_csv -> apply some changes (for example append sth)-> Write data frame to file with to_csv

create an empty dataframe and append it there.. after that u can use .to_csv to export it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM