Home > other >  Python - Operations in Pandas Dataframe
Python - Operations in Pandas Dataframe

Time:12-28

enter image description here

I have this dataframe which is read from an excel file:

I want to know the value of a given column, apply rules, then update it. I'm trying this:

ticker='BTCUSDT'
print(df.at[ticker,'Position'])

#Then, I want to update that value:

df.at[ticker,'Position']=1

When i do this, i get a Key Error. In this example: KeyError: 'BTCUSDT'

Expected:

print=0
cell after assign = 1

This works, however, if I first assign a value to the cell, in example:

if first i do this:

ticker='BTCUSDT'
df.at['BTCUSDT','Position']=0
#then this works:

ticker='BTCUSDT'
df.at[ticker,'Position']

df.at[ticker,'Position']=1

What am I doing wrong ?

Thanks in advance.

CodePudding user response:

Ticker is not the Index but just a column. If you do df = df.set_index('Ticker') yoi should be good

CodePudding user response:

The following code will look for the ticker value BTCUSDT within the Ticker column,
and change the value in the associated Position column to 1.

Code:

ticker='BTCUSDT'
df.loc[df['Ticker'] == ticker, 'Position'] = 1


For example:

If you have the following dataframe:

df = pd.DataFrame({ 'Ticker': ['BTCBUSD', 'ETHBUSD', 'LTCBUSD', 'SOLBUSD', 'FIMUSDT'],
                    'Position': [0,0,0,0,0],
                    'Quantity': [0,0,0,0,0],
                    'Price':[0,0,0,0,0]})

You can update the position value of BTCBUSD to 1 in the same way using:

ticker='BTCBUSD'
df.loc[df['Ticker'] == ticker, 'Position'] = 1
print(df)

Output:

Updated dataframe

  • Related