Python 检查完整性和最新版本-数据帧
我有一个带有产品描述、零件号id、零件总数和产品版本的数据框Python 检查完整性和最新版本-数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个带有产品描述、零件号id、零件总数和产品版本的数据框 *product part_id total_parts version* Product1 1 3 0 Product1 2 3 0 Product2 1 1 0 Product2 1 1 1 Product3 1 2 0 Produ
*product part_id total_parts version*
Product1 1 3 0
Product1 2 3 0
Product2 1 1 0
Product2 1 1 1
Product3 1 2 0
Product3 2 2 0
我想增加两列。一个标记是否所有零件都在df中(完整),另一个标记是否是产品的最新版本(是否最新)
结果应该是这样的:
*product part_id total_parts version* complete is_the_latest
Product1 1 3 0 N Y
Product1 2 3 0 N Y
Product2 1 1 0 Y N
Product2 1 1 1 Y Y
Product3 1 2 0 Y Y
Product3 2 2 0 Y Y
版本可以在0到4之间。零件可以在1到250之间。如何创建这些标志?请尝试:
import numpy as np
import pandas as pd
df = pd.DataFrame({
'product': {0: 'Product1', 1: 'Product1', 2: 'Product2',
3: 'Product2', 4: 'Product3', 5: 'Product3'},
'part_id': {0: 1, 1: 2, 2: 1, 3: 1, 4: 1, 5: 2},
'total_parts': {0: 3, 1: 3, 2: 1, 3: 1, 4: 2, 5: 2},
'version': {0: 0, 1: 0, 2: 0, 3: 1, 4: 0, 5: 0}
})
# Groupby product
g = df.groupby('product')
# Check if number of unique part ids matches expected number of parts
df['complete'] = np.where(
g['part_id'].transform('nunique').eq(df['total_parts']),
'Y',
'N'
)
# Check that the max version equals the current version
df['is_the_latest'] = np.where(
g['version'].transform('max').eq(df['version']),
'Y',
'N'
)
print(df)
df
:
product part_id total_parts version complete is_the_latest
0 Product1 1 3 0 N Y
1 Product1 2 3 0 N Y
2 Product2 1 1 0 Y N
3 Product2 1 1 1 Y Y
4 Product3 1 2 0 Y Y
5 Product3 2 2 0 Y Y
您在两个新列中将标志设置为“Y”或“N”的条件是什么?当所有零件都存在时,同一产品的所有行的“完成”列应为Y。因此,如果产品有4个部分,如果我们有第1、2、3和4部分。”完成“=”Y“。is_最新列对于版本为最新的同一项目中的所有行都应为“Y”。因此,如果我们有两个版本的Product2,那么版本为0的行必须在最新列is_中填入“N”。只有版本为1的Product2的行应填写“Y”。