我有两个数据集:
第一个数据集如下所示:
| Key 1 | Value 1 | Key 2 | Value 2 | Key 3 | Value 3|
| abc | True | bcd | False | cde | False |
| bcd | False | cde | True | def | False |
| def | False | abc | True | None | N/A |第二个数据如下:
| abc | bcd | cde | def | status |
| False | False | True | False | Success |
| True | False | False | False | Failure |
| False | True | True | True | Success |
| False | False | True | False | Failure |
| True | False | False | False | Success |
| False | True | True | True | Success |
| False | False | True | True | Success |
| True | False | False | False | Failure |
| True | True | True | False | Failure |现在,对于第一个数据集中的每一行,我希望拾取键值对,并将它们作为过滤器应用到第二个数据集中,即从第二个子集中提取行。然后计算适用的行数,否。成功,而不是失败。
因此,第一个数据集转换为:
| Key 1| Value 1| Key 2| Value 2| Key 3| Value 3| Row Count | Successes| Failures|
| abc | True | bcd | False | cde | False | 3 |1 |2 |
| bcd | False | cde | True | def | False | 2 |1 |1 |
| def | False | abc | True | None | N/A | 4 |1 |3 |解释:
在第一行(第一组数据)中: abc;bcd - False;cde - False。在第二个数据集中应用这些筛选器,我们将被排除在以下行之外:
| abc | bcd | cde | def | status |
| True | False | False | False | Failure |
| True | False | False | False | Success |
| True | False | False | False | Failure |行数:3失败:2成功:1
发布于 2019-02-14 09:47:45
我相信你需要:
from collections import Counter
#create dictionaries of boolean values for each row
L = [{a:b for a, b in (zip(v[::2], v[1::2])) if isinstance(b, bool)}
for k, v in df1.T.to_dict('l').items()]
print (L)
[{'abc': True, 'bcd': False, 'cde': False},
{'bcd': False, 'cde': True, 'def': False},
{'def': False, 'abc': True}]
#match with df2 and count index values by Counter
df22 = df2.set_index('status')
out = [Counter(df22.index[np.logical_and.reduce([df22[k] == v
for k, v in x.items()])]) for x in L]
print (out)
[Counter({'Failure': 2, 'Success': 1}),
Counter({'Success': 1, 'Failure': 1}),
Counter({'Failure': 3, 'Success': 1})]
#create DataFrame
df2 = pd.DataFrame(out, index=df1.index).fillna(0).astype(int)
#insert total row for first position
df2.insert(0, 'Row Count', df2.sum(axis=1))
#join together
df = df1.join(df2)
print (df)
Key 1 Value 1 Key 2 Value 2 Key 3 Value 3 Row Count Failure Success
0 abc True bcd False cde False 3 2 1
1 bcd False cde True def False 2 1 1
2 def False abc True None NaN 4 3 1https://stackoverflow.com/questions/54685246
复制相似问题