【问题标题】:Python pandas: replace values based on location not index valuePython pandas:根据位置而不是索引值替换值
【发布时间】:2021-06-08 02:24:24
【问题描述】:

这是我的 df:

In[12]: df  = pd.DataFrame(data = list("aabbcc"), columns = ["s"], index=range(11,17))
In[13]: df
Out[13]: 
    s
11  a
12  a
13  b
14  b
15  c
16  c

让我们尝试根据索引替换值:

In[14]: df.loc[11, "s"] = 'A'
In[15]: df
Out[15]: 
    s
11  A
12  a
13  b
14  b
15  c
16  c
In[16]: df.ix[12, "s"] = 'B'
In[17]: df
Out[17]: 
    s
11  A
12  B
13  b
14  b
15  c
16  c

有效!但是如果我根据位置而不是索引做同样的事情,说这样的话,但它显示 ValueError (ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]):

In[18]: df.iloc[1, "s"] = 'b'

而且,如果我尝试这样的事情:

df.s.iloc[1] = "b"

我收到此警告:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

【问题讨论】:

  • 您遇到的第一个错误是因为您尝试对字符串使用基于整数的索引。试试df.iloc[1, 0] = 'b'。这是您正在运行的完整代码吗? df.s.iloc[1] = "b" 在我运行它时不会产生错误。如果df 是通过切片另一个数据框创建的,我希望看到您收到的警告。

标签: python pandas


【解决方案1】:

您可以使用 get_loc 获取列的位置并将其传递给 iloc:

df.iloc[1, df.columns.get_loc('s')] = 'B'

df
Out: 
    s
11  a
12  B
13  b
14  b
15  c
16  c

或者反过来:

df.loc[df.index[1], 's'] = 'B'

【讨论】:

  • 我无法理解这种行为的设计。为什么通过额外的函数调用强制用户提供命名列的索引是有意义的?
猜你喜欢
  • 2016-10-10
  • 2019-03-22
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多