python - 比较 Pandas 数据框中一行中的列值
问题描述
我有一个要解决的具体问题和一般问题。
具体问题: 我想在数据框中创建一个新列,如果列 C1 为 8,并且该行中的所有其他值都小于 8,则该列给出 1。我如何在逻辑上同时否定所有其他列?这是我有缺陷的尝试的代码:
df["C1is_8"] = df.apply(lambda row:(row['C1']==8)& ~(row['C1']<8) ,axis=1).astype(int)
下面的代码为上面的代码生成数据帧。
dict = { 'C1':[4,3,0,0,2,3,4,5,8,8,8,8],
'C2':[8,3,3,7,6,5,3,5,6,8,8,8],
'C3':[2,3,6,4,5,0,0,4,6,7,8,8],
'C4':[8,5,4,4,4,3,2,1,4,2,6,8]
}
columns = ['C1','C2','C3','C4']
Index = [1,2,3,4,5,6,7,8,9,10,11,12]
df = pd.DataFrame(dict,index = Index,columns = columns)
df = OGdf[::-1]
df
一般问题:我如何重写上面代码的某个版本,以便我可以概括它(即 row[i] ),以便它可以应用于任何列,而不仅仅是'C1'?
解决方案
我认为这个答案可以满足您的具体问题和一般问题,使用filter
and all
:
# define the column you want to apply your first condition to
col = 'C1'
# Python 3.6 or above, with f-strings:
df['new_col'] = ((df[col] == 8) & (df.filter(regex=f'[^{col}]') < 8).all(1)).astype(int)
# Otherwise:
df['new_col'] = ((df[col] == 8) & (df.filter(regex='[^{}]'.format(col)) < 8).all(1)).astype(int)
>>> df
C1 C2 C3 C4 new_col
1 4 8 2 8 0
2 3 3 3 5 0
3 0 3 6 4 0
4 0 7 4 4 0
5 2 6 5 4 0
6 3 5 0 3 0
7 4 3 0 2 0
8 5 5 4 1 0
9 8 6 6 4 1
10 8 8 7 2 0
11 8 8 8 6 0
12 8 8 8 8 0
推荐阅读
- java - 带有 ListView 的片段始终为空 Android
- java - 如何在 java 中实现 Postgresql 特定功能,hibernate 不支持(VALUES 表达式)
- vb.net - 在 VB.NET 中获取本地 IP 地址 (IPV4) - 错误“此类型已过时解析”较新版本
- php - 如何使用php从标签内的表单中突出显示字符串内容
- c - 缺陷查找器 - 2 个错误溢出缓冲区 (char,strlen)
- python - 如何获取 pandas 中附加/合并 DataFrame 中的行数?
- laravel - 在 Laravel 中使用 foreach 上传文件
- r - 如何从 github 直接检索 tsv 文件到我的 R 会话?
- c# - 在 ASP.NET MVC 应用程序中通过 USB 摄像头读取二维码
- centos7 - 找不到心跳包.centos