简体   繁体   English

pandas,更改 dataframe 中的特定单元格

[英]pandas,change particular cell in dataframe

How to change particular cell in dataframe?如何更改 dataframe 中的特定单元格?

issue:问题:

a new row is adding,instead of modifying the old data

when I try to change it like,当我尝试改变它时,

d1.at[0, 'high'] = 10

Assume that your DataFrame ( d1 ) contains something like:假设您的 DataFrame ( d1 ) 包含以下内容:

   high  low
1     1    2
2     3    4
3     5    6

Note that the index does not contain 0 .请注意,索引包含0

Then, when you run d1.at[0, 'high'] = 10 , Pandas operates the following way:然后,当您运行d1.at[0, 'high'] = 10时, Pandas的运行方式如下:

  • Attempt to find a row with index 0 .尝试查找索引为0的行。
  • If the DataFrame in question does not contain such a row then add a row with such index and all columns set initially to NaN .如果有问题的 DataFrame 不包含这样的行,则添加具有此类索引的行,并且所有列最初都设置为NaN
  • In the (just added) row set value in high column to 10 .在(刚刚添加的)行中,将列中的值设置为10
  • Other columns (in this case only low ) have not been set, so they still have NaN .其他列(在这种情况下只有low )尚未设置,因此它们仍然具有NaN
  • A side effect is that both columns were of int type.副作用是列都是int类型。 But even the initial, temporary setting of any of their elements to NaN coerces these columns to float .但即使将它们的任何元素初始临时设置为NaN也会强制这些列浮动

So after the above instruction d1 contains:所以在上述指令d1之后包含:

   high  low
1   1.0  2.0
2   3.0  4.0
3   5.0  6.0
0  10.0  NaN

And then let's test another scenario:然后让我们测试另一个场景:

d1 does contain a row with index 0 : d1确实包含索引为0的行:

   high  low
1     1    2
2     3    4
3     5    6
0     7    8

Now if you run d1.at[0, 'high'] = 10 a "wanted" row has been found (no insertion took place) and high column in this row has been set to 10 (other columns in these row keep their initial values).现在,如果您运行d1.at[0, 'high'] = 10已找到“想要的”行(未发生插入)并且该行中的列已设置为10 (这些行中的其他列保持其初始值)。

After that d1 contains:之后d1包含:

   high  low
1     1    2
2     3    4
3     5    6
0    10    8

so:所以:

  • Pandas updated the column in question, Pandas更新了有问题的列,
  • both columns keep their initial types.两列都保持其初始类型。

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

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