首页 > 解决方案 > 有没有办法可以缩小这段代码?我想比较我的输入列表是否存在于我的数据框中

问题描述

我的代码:

input = list([0,0,0,1,1,3])

CVDdata[(CVDdata['Diabetic']==input[0]) & (CVDdata['Gender']==input[1]) & (CVDdata['Smoker']==input[2]) & (CVDdata['Age']==input[3]) & (CVDdata['Cholesterol']==input[4]) & (CVDdata['SBP']==input[5])]['Risk %']

如何将列表与行进行比较?

标签: pythonpandas

解决方案


一个解决方案可能是:

import numpy as np
import pandas as pd

np.random.seed(42)

# Assume this is your data
# If your data contains other columns, you can filter these columns.
# data = original_data[['Diabetic', 'Gender', 'Smoker', 'Age', 'Cholesterol', 'SBP']]
data = pd.DataFrame(np.random.randint(low=0, high=5, size=(10, 6)),
                    columns=['Diabetic', 'Gender', 'Smoker', 'Age', 'Cholesterol', 'SBP'])
print(data)
   Diabetic  Gender  Smoker  Age  Cholesterol  SBP
0         3       4       2    4            4    1
1         2       2       2    4            3    2
2         4       1       3    1            3    4
3         0       3       1    4            3    0
4         0       2       2    1            3    3
5         2       3       3    0            2    4
6         2       4       0    1            3    0
7         3       1       1    0            1    4
8         1       3       3    3            3    4
9         2       0       3    1            3    1

# Your input list
check = list([0, 2, 2, 1, 3, 3])

print(data[data == check].dropna(axis=0, how='any'))
   Diabetic  Gender  Smoker  Age  Cholesterol  SBP
4       0.0     2.0     2.0  1.0          3.0  3.0

推荐阅读