Pandas 使用类列表索引器赋值
Pandas assigning value with list-like indexer
我有一个问题已在 2014 年得到处理:See @jeff answer。但是我想知道从那以后事情是否发生了变化。
我编写的代码对我有效但对同事无效:
df2 = pd.DataFrame({'A': ["yes", "no", "yes", "no"], 'B': [1,2,1,3]})
A B
0 yes 1
1 no 2
2 yes 1
3 no 3
df = pd.DataFrame({'A': [7,5,9,4], 'B': [4,4,4,4]})
A B
0 7 4
1 5 4
2 9 4
3 4 4
df[df2["A"] == "yes"] = np.full(2, 20.0) * df.values[2]
这非常适合我,并为我提供了所需的输出:
A B
0 180 80
1 5 4
2 180 80
3 4 4
但是 returns 我同事的一个错误:
ValueError: cannot set using a list-like indexer with a different length than the value
这就是@Jeff 在他的回答中所描述的 "Bottom line, don't use lists inside of a pandas object. Its not efficient, and just makes interpretation difficult / impossible."
pandas 中是否有任何更改现在允许这种编码方式?我没有在文档中找到任何警告这种可能的错误解释的内容。
如果这仍然是一种不好的做法,那么最佳做法是什么?
我认为您引用的答案与您的问题无关。这里你分配了一个 np.array 形状 (2,)
:
(np.full(2, 20.0) * df.values[2]).shape
到形状为 (2,2)
:
的 np 数组
(df[df2["A"] == "yes"]).shape
numpy 广播规则处理得很好。 @Jeff 的回答是关于普通列表
所以我认为您的同事只需要升级 pandas 或 numpy 或两者。您可以通过 eg
检查版本(在终端中)
pip show pandas
pip show numpy
或在 Jupyter notebook 中通过
!pip show pandas
!pip show numpy
你的代码适用于最新版本(对我来说 pandas 1.2.2 和 numpy 1.19.5
我有一个问题已在 2014 年得到处理:See @jeff answer。但是我想知道从那以后事情是否发生了变化。
我编写的代码对我有效但对同事无效:
df2 = pd.DataFrame({'A': ["yes", "no", "yes", "no"], 'B': [1,2,1,3]})
A B
0 yes 1
1 no 2
2 yes 1
3 no 3
df = pd.DataFrame({'A': [7,5,9,4], 'B': [4,4,4,4]})
A B
0 7 4
1 5 4
2 9 4
3 4 4
df[df2["A"] == "yes"] = np.full(2, 20.0) * df.values[2]
这非常适合我,并为我提供了所需的输出:
A B
0 180 80
1 5 4
2 180 80
3 4 4
但是 returns 我同事的一个错误:
ValueError: cannot set using a list-like indexer with a different length than the value
这就是@Jeff 在他的回答中所描述的 "Bottom line, don't use lists inside of a pandas object. Its not efficient, and just makes interpretation difficult / impossible."
pandas 中是否有任何更改现在允许这种编码方式?我没有在文档中找到任何警告这种可能的错误解释的内容。
如果这仍然是一种不好的做法,那么最佳做法是什么?
我认为您引用的答案与您的问题无关。这里你分配了一个 np.array 形状 (2,)
:
(np.full(2, 20.0) * df.values[2]).shape
到形状为 (2,2)
:
(df[df2["A"] == "yes"]).shape
numpy 广播规则处理得很好。 @Jeff 的回答是关于普通列表
所以我认为您的同事只需要升级 pandas 或 numpy 或两者。您可以通过 eg
检查版本(在终端中)pip show pandas
pip show numpy
或在 Jupyter notebook 中通过
!pip show pandas
!pip show numpy
你的代码适用于最新版本(对我来说 pandas 1.2.2 和 numpy 1.19.5