简体   繁体   中英

Python - Operations in Pandas Dataframe

在此处输入图像描述

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.

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

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:

更新数据框

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