简体   繁体   English

给定索引值的1列中的Pandas DataFrame替换值

[英]Pandas DataFrame replace value in 1 column given an index value

This seems like something simple. 这似乎很简单。 But I've tried several different things and read probably a dozen StackOverflow questions that seemed related. 但是我已经尝试了几种不同的方法,并且阅读了可能有关的12个StackOverflow问题。

I have market data for crypto currnecies (BitCoin and others). 我有加密货币(比特币等)的市场数据。 The Order Book is a list of all the 'asks' and 'bids' for a given currency. 订单簿是给定货币的所有“询问”和“出价”的列表。 I am wanting to store the data in a Pandas DataFrame. 我想将数据存储在Pandas DataFrame中。 (I'm not stuck on using DFs just thought it might provide easier plotting down the road.) (我并不只是在使用DF,因为它可能会简化绘制路线的工作。)

So the setup right now is a DataFrame where the Rate (price) is the Index and it is a float. 因此,现在的设置是一个DataFrame,其中Rate(价格)是Index,它是一个float。 The quantity of coins available at that price is in a column named Amt. 在该价格下可用的硬币数量在名为Amt的列中。

When I get an update to the Amount at a given Rate I want to simply replace that value. 当我以给定的汇率更新金额时,我想简单地替换该值。 Of all the possible solutions I found this option to be the most intuitive to me: 在所有可能的解决方案中,我发现此选项对我来说是最直观的:

df.Amt[df.Rate == rate] = new_amt

While I don't get any errors from this, when I check to see if the Amt changes I find that it has not. 虽然我没有从中得到任何错误,但是当我检查Amt是否更改时,我发现它没有更改。 I assume this is one of those copy/slice issues vs working on the DataFrame itself. 我认为这是复制/切片问题之一,而不是在DataFrame本身上工作。

Example: 例:

df.head()
Out[77]: 
       Rate        Amt
0  0.018021   0.319033
1  0.018009  29.994000
2  0.017999  28.121000
3  0.018042   2.233781
4  0.018055  13.433394

df.Amt[df.Rate == 0.018021] = 20

df.head()
Out[79]: 
       Rate        Amt
0  0.018021   0.319033
1  0.018009  29.994000
2  0.017999  28.121000
3  0.018042   2.233781
4  0.018055  13.433394

What am I missing? 我想念什么? I've worked with DFs in the past to change whole columns but not generally just 1 row. 过去,我曾与DF一起更改过整列,但通常不更改一列。

Correcting the error and incorporating @JohnE's comment 更正错误并合并@JohnE的注释

You were accessing the pd.Series object with df.Amt and slicing it with [df.Rate == 0.018021] . 你被访问pd.Series与对象df.Amt与切片它[df.Rate == 0.018021] When what you want is to pass the boolean array to loc and assign that way. 当您想要的是将布尔数组传递给loc并进行分配时。

df.loc[np.isclose(df.Rate, 0.018021), 'Amt'] = 20

       Rate        Amt
0  0.018021  20.000000
1  0.018009  29.994000
2  0.017999  28.121000
3  0.018042   2.233781
4  0.018055  13.433394

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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