[英]How to create a new Pandas dataframe from a filtered list?
我想知道如何根據一組值創建一個新的數據框。
給定一個值數組:
x1 = ['apple', 'orange', 'banana']
並給出一個數據框:
index, fruit, foo, bar
0, apple, true, false
1, pineapple, false, true
2, orange, true, true
3, banana, true, true
4, pear, true, true
如何創建一個只包含數組 x1 值的新數據框?
Output數據幀:
index, fruit, foo, bar
0, apple, true, false
1, orange, true, true
2, banana, true, true
我認為您需要pandas.Series.isin(values)
可用於檢查Series 中的元素是否包含在值中。
>>> import pandas as pd
>>>
>>> df = pd.DataFrame(
... {"fruit": ["apple", "pineapple", "orange"], "foo": ["true", "false", "true"]}
... )
>>>
>>> df
fruit foo
0 apple true
1 pineapple false
2 orange true
>>> df[df.fruit.isin(['apple', 'orange', 'banana'])]
fruit foo
0 apple true
2 orange true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.