python-3.x - 熊猫数据框组检查一列的唯一值的数量是否为一但排除空字符串
问题描述
我有以下df
,
id invoice_no
1 6636
1 6637
2 6639
2 6639
3
3
4 6635
4 6635
4 6635
invoice_no
for id
3 都是空字符串或空格;我想要
df['same_invoice_no'] = df.groupby("id")["invoice_no"].transform('nunique') == 1
invoice_no
但也将每组中的空格和空字符串视为same_invoice_no = False
;我想知道该怎么做。结果看起来像,
id invoice_no same_invoice_no
1 6636 False
1 6637 False
2 6639 True
2 6639 True
3 False
3 False
4 6635 True
4 6635 True
4 6635 True
解决方案
空字符串等于 True 但 NaN 不等于。用 Numpy nan 替换空字符串
df.replace('', np.nan, inplace = True)
df['same_invoice_no'] = df.groupby("id")["invoice_no"].transform('nunique') == 1
id invoice_no same_invoice_no
0 1 6636.0 False
1 1 6637.0 False
2 2 6639.0 True
3 2 6639.0 True
4 3 NaN False
5 3 NaN False
6 4 6635.0 True
7 4 6635.0 True
8 4 6635.0 True
推荐阅读
- android - 更新到 AS 3.3 后“PKIX 路径构建失败”
- fonts - “不存在支持的字形形状表”[OpenType 字体]
- php - 如何在本地网络上共享一个 laravel 项目
- c# - 如何使用 C# 将数据从网站检索到我的 winforms
- c# - 如何挂钩事件或 WPF 应用程序中窗口的更改?
- linux - centos7我设置了这个脚本开机,重启后服务没有启动
- angular-reactive-forms - 如何将 formControlName 绑定到静态单选按钮值
- ios - iOS BLE 后台执行时间
- reactjs - 如何创造新的 Const 并推动价值?反应
- php - Laravel:在 \Illuminate\Support\Facades\Schema 中找不到方法“defaultStringLength”