Pra*_*tta 6 python conditional-statements dataframe pandas
我有一个数据框:
df = pd.DataFrame({
'col1': [0.1, 0.8, 0.2, 0.12],
'col2': [0.2, 0.9, 0.1, 0.1],
'col3': [0.3, 0.2, 0.1, 0.2],
'col4': [0.6, 0.7, 0.8, 0.9]
})
col1 col2 col3 col4
0 0.10 0.2 0.3 0.6
1 0.80 0.9 0.2 0.7
2 0.20 0.1 0.1 0.8
3 0.12 0.1 0.2 0.9
Run Code Online (Sandbox Code Playgroud)
我想找到那些至少有一个行值大于 0.7 而其余所有行值小于 0.3 的列值。在上面的代码片段中,结果应该是:
['col1', 'col2']
Run Code Online (Sandbox Code Playgroud)
我尝试过以下代码:
selected_cols = []
for col in df.columns:
values = df[col]
if any(values > 0.7) and all(values < 0.3):
selected_cols.append(col)
print(selected_cols)
Run Code Online (Sandbox Code Playgroud)
尝试:
x = (df > 0.7).sum()
y = (df < 0.3).sum()
z = (x == 1) & (y == len(df) - 1)
print(z[z].index.to_list())
Run Code Online (Sandbox Code Playgroud)
印刷:
['col1', 'col2']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
298 次 |
| 最近记录: |