pandas - 我如何检查特定列是否具有任何行的相似值,. 一个类似的例子,这种情况是 456 类似于 654
问题描述
我从一个示例数据框开始,并尝试检查该列中任何值的总和对于所有行集是否相同
#### load data###
import pandas as pd
df=pd.DataFrame(iris.data,columns=iris.feature_names)
df.head()
这给了我一个错误“系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。” 并且也不考虑所有行
m=df.shape[0]
columns = [0]
df.iloc[2, :] = [3, 4, 5, 1]
df.iloc[3, :] = [3, 4, 4, 1]
for row1 in range(m-1):
for row2 in range(row1+1, m):
if (df.iloc[row1,columns].sum == df.iloc[row2, columns].sum).all():`
# logic
print ('Good!')
else:
print(f"nothing")
不幸的是,这里的 sum 函数不检查每行,我不确定如何做到这一点
解决方案
Map
一个添加数字的函数,然后用于np.where
分配'Good!'
值的位置duplicated
。
在:
df = pd.DataFrame({'data': [456,654,235,532,111,354]})
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
df['status'] = np.where(df.data.map(sum_digits).duplicated(keep=False), 'Good!', 'nothing')
出去:
data status
0 456 Good!
1 654 Good!
2 235 Good!
3 532 Good!
4 111 nothing
5 354 nothing
推荐阅读
- perl - 我可以从 perl 的进程中捕获 STDOUT 写入事件吗?
- proxy - 将 CORSHandler 添加到骆驼码头组件
- regex - 正则表达式在 Java 中获取与“-”或“/”组合的值
- javascript - PHP 没有从 HTML 联系表单中提取输入
- qt-creator - 将自定义关键字 C++ 添加到 qtcreator
- javascript - 为什么我不能在 JavaScript 中设置导航栏的高度?
- angular - 按字母顺序显示 json 数据
- realm - 在 Electron JS 应用程序上使用来自 npm 的 Realm
- angular - 如何根据angular4中的下拉选择进行路由?
- java - JMX 获取实时堆内存使用报告常量值