select multiple rows by index in pandas if it is in a list
First change list
to another name like L
, because list
is a reserved word in Python. Then select by DataFrame.loc
for selecting by labels:
L=[12,15,10,14]
df = df.loc[L]
print (df)
A B
12 2 c
15 5 f
10 0 a
14 4 e
Your solution is close for select by positions with DataFrame.iloc
function:
L1 = [2,5]
df = df.iloc[L1]
print (df)
A B
12 2 c
15 5 f
Python: Pandas Dataframe select row by given index
Just use .loc
:
>>> df.loc['2a']
col1 20.2
col2 30.5
Name: 2a, dtype: float64
>>> df.loc['2a', 'col1']
20.2
Select rows of pandas dataframe from list, in order of list
One way to overcome this is to make the 'A'
column an index
and use loc
on the newly generated pandas.DataFrame
. Eventually, the subsampled dataframe's index can be reset.
Here is how:
ret = df.set_index('A').loc[list_of_values].reset_index(inplace=False)
# ret is
# A B
# 0 3 3
# 1 4 5
# 2 6 2
Note that the drawback of this method is that the original indexing has been lost in the process.
More on pandas
indexing: What is the point of indexing in pandas?
Use a list of values to select rows from a Pandas dataframe
You can use the isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
Select rows of pandas dataframe in order of a given list with repetitions and keep the original index
We have to preserve the index
by assigning it as a column first so we can set_index
after the mering:
list_of_values = [3, 4, 6, 4, 3, 8]
df2 = pd.DataFrame({'A': list_of_values, 'order': range(len(list_of_values))})
dfn = (
df.assign(idx=df.index)
.merge(df2, on='A')
.sort_values('order')
.set_index('idx')
.drop('order', axis=1)
)
A B
idx
2 3 3
3 4 5
1 6 2
3 4 5
2 3 3
If you want to get rid of the index name (idx
), use rename_axis
:
dfn = dfn.rename_axis(None)
A B
2 3 3
3 4 5
1 6 2
3 4 5
2 3 3
select pandas rows by excluding index number
Not sure if that's what you are looking for, posting this as an answer, because it's too long for a comment:
In [31]: d = {'a':[1,2,3,4,5,6], 'b':[1,2,3,4,5,6]}
In [32]: df = pd.DataFrame(d)
In [33]: bad_df = df.index.isin([3,5])
In [34]: df[~bad_df]
Out[34]:
a b
0 1 1
1 2 2
2 3 3
4 5 5
Index rows in Pandas Dataframe not in List of Indexes (Python)
Try this:
data.loc[~ data.index.isin(idx)]
Filter data frame based on index value in Python
try this:
Filter_df = df[df.index.isin(my_list)]
Related Topics
How to Convert a File to Utf-8 in Python
E731 Do Not Assign a Lambda Expression, Use a Def
How to Extract Data from Matplotlib Plot
What's a Faster Operation, Re.Match/Search or Str.Find
Count Unique Values Using Pandas Groupby
How to Make Python Scripts Executable on Windows
How to Use SQL Parameters with Python
Removing Duplicates from Dictionary
Downloading with Chrome Headless and Selenium
Take Screenshot of Full Page with Selenium Python with Chromedriver
How to Write Binary Data to Stdout in Python 3
Parsing a JSON String Which Was Loaded from a CSV Using Pandas
How to Pass an Argument to a Function Pointer Parameter
Streaming Data with Python and Flask
How to Check If One Two-Dimensional Numpy Array Contains a Specific Pattern of Values Inside It
How to Convert an Array of Strings to an Array of Floats in Numpy
How to Install Python 3.X and 2.X on the Same Windows Computer