[英]Python - Operations in Pandas Dataframe
I have this dataframe which is read from an excel file:我有这个 dataframe,它是从 excel 文件中读取的:
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 .当我这样做时,我得到一个Key Error 。 In this example:
KeyError: 'BTCUSDT'
在这个例子中:
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. Ticker 不是索引,而只是一列。 If you do
df = df.set_index('Ticker')
yoi should be good如果你这样做
df = df.set_index('Ticker')
你应该很好
The following code will look for the ticker value BTCUSDT
within the Ticker
column,以下代码将在
Ticker
列中查找代码值BTCUSDT
,
and change the value in the associated Position
column to 1
.并将关联的
Position
列中的值更改为1
。
ticker='BTCUSDT'
df.loc[df['Ticker'] == ticker, 'Position'] = 1
If you have the following dataframe:如果您有以下 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:您可以使用相同的方式将 BTCBUSD 的
BTCBUSD
值更新为1
:
ticker='BTCBUSD'
df.loc[df['Ticker'] == ticker, 'Position'] = 1
print(df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.