Skip to content
Fix Code Error

Selecting a row of pandas series/dataframe by integer index

March 13, 2021 by Code Error
Posted By: user1642513

I am curious as to why df[2] is not supported, while df.ix[2] and df[2:3] both work.

In [26]: df.ix[2]
Out[26]: 
A    1.027680
B    1.514210
C   -1.466963
D   -0.162339
Name: 2000-01-03 00:00:00

In [27]: df[2:3]
Out[27]: 
                  A        B         C         D
2000-01-03  1.02768  1.51421 -1.466963 -0.162339

I would expect df[2] to work the same way as df[2:3] to be consistent with Python indexing convention. Is there a design reason for not supporting indexing row by single integer?

Solution

echoing @HYRY, see the new docs in 0.11

http://pandas.pydata.org/pandas-docs/stable/indexing.html

Here we have new operators, .iloc to explicity support only integer indexing, and .loc to explicity support only label indexing

e.g. imagine this scenario

In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB'))

In [2]: df
Out[2]: 
          A         B
0  1.068932 -0.794307
2 -0.470056  1.192211
4 -0.284561  0.756029
6  1.037563 -0.267820
8 -0.538478 -0.800654

In [5]: df.iloc[[2]]
Out[5]: 
          A         B
4 -0.284561  0.756029

In [6]: df.loc[[2]]
Out[6]: 
          A         B
2 -0.470056  1.192211

[] slices the rows (by label location) only

Answered By: Anonymous

Related Articles

  • Change column type in pandas
  • How are iloc and loc different?
  • Pandas - Get first row value of a given column
  • Reference — What does this symbol mean in PHP?
  • Can't install via pip because of egg_info error
  • How to return a list from a pos tag column?
  • Can't stratify output in a customized way
  • What does this symbol mean in JavaScript?
  • Pandas Merging 101
  • Proper way to assigning new columns to a dataframe
  • Select DataFrame rows between two dates
  • Creating a dataframe of two loops using haversine…
  • In Pandas, how do I convert a number column to…
  • Why does .loc not always match column names?
  • When I'm testing a web app by JUnit and Mockito I…
  • Rolling Average Home and Away
  • Selection with .loc in python
  • Create a day-of-week column in a Pandas dataframe…
  • What's the difference between eval, exec, and compile?
  • Efficient way to apply multiple filters to pandas…
  • Pandas multi-index unstack to single row
  • Replacing nested loops over a dataframe with…
  • Access PostgreSQL hstore keys and values in Python…
  • Pandas - DF with lists - find all rows that match a…
  • How do I divide values across dataframes in pandas?
  • Merge 2 dataframes of different sizes after a…
  • Calculate repeat purchase probability
  • How to deal with SettingWithCopyWarning in Pandas
  • Dataframe count set of conditions passed by several…
  • How to take column-slices of dataframe in pandas
  • Get total of Pandas column
  • Pandas pivot_table: filter on aggregate function
  • Creating a dataframe of many loops within loops for…
  • Python Pandas - Time Series Find Index of Previous Row
  • UnsatisfiedDependencyException: Error creating bean…
  • How can I pass a wct test while rearranging children…
  • Convert pandas.Series from dtype object to float,…
  • What are the new features in C++17?
  • How do I split out a multi-index dataframe with a…
  • org.springframework.beans.factory.NoSuchBeanDefiniti…
  • How to update dataframe.ix code when refering to dates
  • how to split dataframe cells using delimiter into…
  • Python Pandas: Get index of rows which column…
  • Get first row of dataframe in Python Pandas based on…
  • How to loop through different functions / filter…
  • Splitting dataframe into multiple dataframes
  • Why does this selection sort code shows different…
  • Numbering rows in pandas dataframe (with condition)
  • Error creating bean with name
  • Type of panda.Series
  • How to join dataframe?
  • Make the size of a heatmap bigger with seaborn
  • why can't I select inner level index elements in a…
  • How to combine the data from two different…
  • Is it possible to move each row to end of same row…
  • how to add a DataFrame to some columns of another DataFrame
  • Examples of GoF Design Patterns in Java's core libraries
  • Pandas counting/adding values by date and id
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Truth value of a Series is ambiguous. Use a.empty,…
  • Adding new column to existing DataFrame in Python pandas
  • Fillna by relating multiple columns using a created function
  • How to update Python?
  • Python - Delete lines from dataframe (pandas)
  • extract column value based on another column pandas…
  • How to convert array column to int array in Pandas?
  • Calculate count of a numeric column into new columns…
  • data.table vs dplyr: can one do something well the…
  • Replacing Pandas or Numpy Nan with a None to use…
  • How do I sum values in a column that match a given…
  • Replacing blank values (white space) with NaN in pandas
  • Modifying a subset of rows in a pandas dataframe
  • find duplicateds and fill column
  • Binning column with python pandas
  • Find row where values for column is maximal in a…
  • Spring Boot - Cannot determine embedded database…
  • Concatenate rows of two dataframes in pandas
  • How to select rows from a DataFrame based on column values
  • Counting values with condition in one DataFrame and…
  • How to duplicate a certain number of values and then…
  • Assigning columns to a hierarchical higher Multiindex level
  • Pandas series remains the same after appending to it…
  • Pandas read_csv low_memory and dtype options
  • Modify slice of multiindex with series
  • Creating an empty Pandas DataFrame, then filling it?
  • Getting zeros for and or statement
  • Export rows from dataframe which contain special characters
  • pandas read_csv and filter columns with usecols
  • For-each over an array in JavaScript
  • How to properly apply a lambda function into a…
  • if and elif for three conditions
  • Plot graph with vertical labels on the x-axis Matplotlib
  • Reading from a .dat file Dataframe in Python
  • How to save a pandas DataFrame table as a png
  • Best way to extract messy HTML tables using BeautifulSoup
  • how to convert a panda dataframe column containing…
  • Pandas: tidy multilevel data
  • Python sort_values (inplace=True) but not really?
  • pandas resample documentation
  • Accessing JSON elements with Python and Pandas

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

WAMP error: Forbidden You don’t have permission to access /phpmyadmin/ on this server

Next Post:

Changing one character in a string

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error