首页 > 解决方案 > 如何在python中从数据集中选择行

问题描述

我有一个数据集,其中有一列只接受 0 和 1 值(请参阅 vegan 和素食列)。

在此处输入图像描述

我想选择值为 1 的记录并创建一个包含所有其他列的新数据集,以便仅为特定餐厅创建散点图。这就是所有记录的外观:

在此处输入图像描述

这是情节的代码:

fig = px.scatter(df, x='review_score', y='number_of_reviews', color='Vegetarian Options',
                 hover_data=['food_type1','restaurant_name'])
fig.show()

标签: python

解决方案


这是创建一个只有值 == 1 并只保留其他列的新数据框的一种方法:

import pandas as pd

row1list = [0, 1, 'rest', 'rant']
row2list = [1, 0, 'rest', 'or rant']
row3list = [0, 1, 'rest', 'stop']
df = pd.DataFrame([row1list, row2list, row3list],
                  columns=['Vegan Options', 'Vegetarian Options', 'col_abc', 'col_xyz'])

for col in ['Vegan Options', 'Vegetarian Options']:
    df_filtered = df[df[col] == 1]    # keep only the rows where col value == 1
    del df_filtered[col]              # delete the column you filtered on



推荐阅读