python - 使用 np.where 匹配 pandas 单元格中的值,其中值是数组(ValueError : Arrays were different lengths)

标签 python arrays pandas numpy dataframe

非常感谢您的阅读。

(事先考虑:我无法更改数据帧内数据的格式;我坚持我所拥有的。以下是我的数据和问题的简化和简化版本)

我有一个具有以下形式的数据框:

df = pd.DataFrame(
{'Machine': [['red', 'blue'], ['red'], ['blue'], ['No Match']]})

       Machine       
0  [red, blue]  
1        [red]   
2       [blue]      
3   [No Match]   

我想创建一个新列 TF,如果 Machine 中的值相等,则对于给定行,该列返回 True否则为 ['No Match']False

       Machine     TF  
0  [red, blue]    False
1        [red]    False
2       [blue]    False
3   [No Match]    True

为此,我可以写:

df['TF'] = np.where(df['Machine'] == ['No Match'],True, False)

我得到这个输出:

ValueError: Arrays were different lengths: 4 vs 1

这样做的原因是 numpy 期望 df['Machine']['No Match'] 具有相同的长度,或者符合右手标准是一个简单的字符串/值。

如何调整此表达式以成功将数组 ['No match'] 作为值传递到 np.where() 语句中?

作为一个有效的示例,对于以下数据框,一切都按预期工作:

df1 = pd.DataFrame(
{'Machine': [['red', 'blue'], ['red'], ['blue'], 'No Match']})

df1['TF'] = np.where(df1['Machine'] == 'No Match',True, False)

按预期工作:

       Machine     TF
0  [red, blue]  False
1        [red]  False
2       [blue]  False
3     No Match   True

最佳答案

您需要使用==apply来检查list中的值:

df['TF'] = np.where(df['Machine'].apply(lambda x: ['No Match'] == x),True, False)
print (df)
       Machine     TF
0  [red, blue]  False
1        [red]  False
2       [blue]  False
3   [No Match]   True

或者如果只需要 TrueFalse 则更简单:

df['TF'] = df['Machine'].apply(lambda x: ['No Match'] == x)
print (df)
       Machine     TF
0  [red, blue]  False
1        [red]  False
2       [blue]  False
3   [No Match]   True

但是如果需要其他值:

df['TF'] = np.where(df['Machine'].apply(lambda x: ['No Match'] == x),'a', 'b')
print (df)
       Machine TF
0  [red, blue]  b
1        [red]  b
2       [blue]  b
3   [No Match]  a

使用列表理解的解决方案:

df['TF'] = [['No Match'] == x for x in df['Machine']]
print (df)
       Machine     TF
0  [red, blue]  False
1        [red]  False
2       [blue]  False
3   [No Match]   True

关于python - 使用 np.where 匹配 pandas 单元格中的值,其中值是数组(ValueError : Arrays were different lengths),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42070410/

相关文章:

c++ - 如何按值对数组进行排序(排序)? *有一个转折*

python - 如何在 Python 中访问聚合函数的值

python - 重采样 Pandas 中的 boolean 值

python - 如何在多张图片中找到一个模板?

python - 我们如何检测 pandas 数据帧中的不一致?

c - 追加到数组末尾

javascript - struts2迭代器值到javascript数组

Python装饰器理论

python - Pandas - 用最少听过的艺术家过滤用户

Python pandas tz_localize throws NonExistentTimeError,然后无法丢弃错误的时间