python - 如何在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()
解决方案
这是创建一个只有值 == 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
推荐阅读
- xamarin - 在 ListView.ItemSource 中点击触发命令
- python - 在哈希表 Django 中传递密码
- php - 意外的 Safari 页面加载计数行为
- php - PHP/CSS 如何实现棋盘格样式
- c++ - Clang++ 已更新,尽管它们位于包含目录中,但仍找不到某些标头
- vue.js - 纱线 monorepo 中的 rollup preserveModules 输出完整的项目路径
- javascript - 将变量从视图传递到控制器ajax
- arrays - HIVEQL 中的 indexOf 相似函数
- php - 使用 WooCommerce 插件的折扣规则时,产品 get_sale_price 始终为 0
- reactjs - React - 测试单独的父组件(没有 redux)