Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Pandas dataframe with MultiIndex: check if string is contained in index level

import numpy as np
import pandas as pd

arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
          np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]

df = pd.DataFrame(np.random.randn(8, 4), index=arrays)


#You can apply mask like this
df = df.iloc[df.index.get_level_values(1).str.contains('ne')]
#OR
df = df.iloc[(df.index.get_level_values(0).str.contains('ba')) | (df.index.get_level_values(1).str.contains('ne'))]
Comment

Pandas dataframe with MultiIndex: check if string is contained in index level

import numpy as np
import pandas as pd

arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
          np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]

df = pd.DataFrame(np.random.randn(8, 4), index=arrays)


#You can apply mask like this
df = df.iloc[df.index.get_level_values(1).str.contains('ne')]
#OR
df = df.iloc[(df.index.get_level_values(0).str.contains('ba')) | (df.index.get_level_values(1).str.contains('ne'))]
Comment

PREVIOUS NEXT
Code Example
Python :: pie plot chance size python 
Python :: python decode errors schemes 
Python :: HTML automation not working on vscode with folder named templates on django 
Python :: Get hours, minutes, seconds, and microseconds using time class 
Python :: How to provide type hinting in UserDict? 
Python :: Indices may also be negative numbers, to start counting from the right:Indices may also be negative numbers, to start counting from the right: 
Python :: remove special characters and numbers from string python 
Python :: Customize tick spacing 
Python :: token validation in flask socket 
Python :: dataframe to DatasetDict 
Python :: poisson random data 
Python :: why do we write f before double quotes in print statement in python 
Python :: matplotlib no gui 
Python :: pandas to_csv adds unnamed column 
Python :: python split get array for loop 
Python :: how to make change the default from python 3.8 to python 3.10.5 on Mint 20 
Python :: sanic ip whitelist 
Python :: matplotlib gfg 
Python :: create date by column values pandas 
Python :: TypeError: strptime() argument 1 must be str, not list 
Python :: loc condition on first 3 columns of dataframe 
Python :: How to Merge QuerySets in Django Rest Framework 
Python :: custom_settings in scrpay 
Python :: tkinter centre a button on 1920x1080 
Python :: convert any .pdf file into audio python dev.to 
Python :: adding attributes and metadata to a dataset using xarray 
Python :: how to check what version of pygame you have instaled 
Python :: decleration of array in python 
Python :: how to get python to write to 100 
Python :: pyspark rdd sort by value descending 
ADD CONTENT
Topic
Content
Source link
Name
6+5 =