[英]Python Pandas : filter a dataframe based on boolean pandas series
I know the topic is very well documented but I did not find a solution good enough. 我知道该主题已得到很好的记录,但是我找不到足够好的解决方案。 I have a boolean pandas series, myboolseries.
我有一个布尔熊猫系列,myboolseries。 I have a dataframe df.
我有一个数据框df。 I want to filter df according to myboolseries (the index where the value is True).
我想根据myboolseries(值为true的索引)过滤df。
myboolseries = pd.Series(data = [True, False, True], index = [2,5,8])
mydic = {"Age" : [14,12,55,22,98], "Name" : ["Pierre", "Mike", "Selena", "Victor", "Jesus"], "index" : [2,14,5,99,8]}
df = pd.DataFrame.from_dict(mydic).set_index("index")
Here is my solution (it does work), but I'm lookin for a more elegant way : 这是我的解决方案(它确实有效),但是我正在寻找一种更优雅的方法:
myboolseries = myboolseries[myboolseries].index
df[myboolseries]
Try: 尝试:
df.loc[df.index.isin(myboolseries.index)][myboolseries]
Age Name
index
2 14 Pierre
8 98 Jesus
You can try this: 您可以尝试以下方法:
df.reindex(myboolseries.loc[lambda x: x].index)
Output: 输出:
Age Name
2 14 Pierre
8 98 Jesus
if your Boolean series is the same length of your DataFrame you can just : 如果您的布尔序列与DataFrame的长度相同,则可以:
df = df[boolseries]
thats it. 而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.