如何在python中从数据集中选择行

2024-09-28 18:51:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,它有一个只接受0和1值的列(请参见纯素和素食列)

enter image description here

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

enter image description here

这是绘图的代码:

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

1条回答
网友
1楼 · 发布于 2024-09-28 18:51:26

有一种方法可以创建一个仅值==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


相关问题 更多 >