python - 根据熊猫列中的逻辑测试从DataFrame中选择行
问题描述
考虑这个数据框
my_input_df = pd.DataFrame({
'export_services': [[1],[],[2,4,5],[4,6]],
'import_services': [[],[4,5,6,7],[],[]],
'seaport':['china','mexico','africa','europe'],
'price_of_fish':['100','150','200','250'],
'price_of_ham':['10','10','20','20']})
我想对布尔值的 export_services 进行过滤(丢弃空列表)并仅输出列的子集
my_output_df = pd.DataFrame({
'export_services': [[1],[2,4,5],[4,6]],
'seaport':['china','africa','europe'],
'price_of_fish':['100','200','250']})
我该怎么办?
谢谢 :)
解决方案
将列转换为布尔值,返回False
s 为空值,因此可loc
用于过滤:
df = my_input_df.loc[my_input_df['export_services'].astype(bool),
['export_services','seaport','price_of_fish']]
print (df)
export_services seaport price_of_fish
0 [1] china 100
2 [2, 4, 5] africa 200
3 [4, 6] europe 250
推荐阅读
- java - 实例化一个包含注解的类
- c# - 无法访问我的方法删除我的 api 休息
- c# - 如何按顺序将项目插入现有的 ListView?(UWP)
- swift - 自定义 segue 到导航控制器
- javascript - jQuery html() 返回空的新输入标签?
- spring - 升级到 Facebook Graph API v2.7 或更高版本
- android - 在 Android 的内部存储中存储大型、复杂、可变的对象
- r - 根据 R 或 SAS 中的条件访问每个元素和表单组
- elasticsearch - Elasticsearch 慢项聚合
- sql-server - SQL Server 使用递归 CTE 获取路径