Pandas interview questions
13 questions with answers. 290 open jobs in India ask for Pandas.
Difference between map, applymap and apply methods in Pandas
applyworks on a row / column basis of a DataFrame
applymapworks element-wise on a DataFrame
mapworks element-wise on a SeriesStraight from Wes McKinney's Python for Data Analysis book, pg. 132 (I highly recommended this book):
Another frequent operation is applying a function on 1D arrays to each column or row. DataFrame’s apply method does exactly this:
In [116]: frame = DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon']) In [117]: frame Out[117]: b d e Utah -0.029638 1.081563 1.280300 Ohio 0.647747 0.831136 -1.549481 Texas 0.513416 -0.884417 0.195343 Oregon -0.485454 -0.477388 -0.309548 In [118]: f = lambda x: x.max() - x.min() In [119]: frame.apply(f) Out[119]: b 1.133201 d 1.965980 e 2.829781 dtype: float64Many of the most common array statistics (like sum and mean) are DataFrame methods, so using apply is not necessary.
Element-wise Python functions can be used, too. Suppose you wanted to compute a formatted string from each floating point value in frame. You can do this with applymap:
In [120]: format = lambda x: '%.2f' % x In [121]: frame.applymap(format) Out[121]: b d e Utah -0.03 1.08 1.28 Ohio 0.65 0.83 -1.55 Texas 0.51 -0.88 0.20 Oregon -0.49 -0.48 -0.31The reason for the name applymap is that Series has a map method for applying an element-wise function:
In [122]: frame['e'].map(format) Out[122]: Utah 1.28 Ohio -1.55 Texas 0.20 Oregon -0.31 Name: e, dtype: objectFrom Stack Overflow: asked by marillion, answered by jeremiahbuddha (CC BY-SA 4.0)
How can I iterate over rows in a Pandas DataFrame?
DataFrame.iterrowsis a generator which yields both the index and row (as a Series):import pandas as pd df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]}) df = df.reset_index() # Make sure indexes pair with number of rows for index, row in df.iterrows(): print(row['c1'], row['c2'])10 100 11 110 12 120Obligatory disclaimer from the documentation
Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed and can be avoided with one of the following approaches:
- Look for a vectorized solution: many operations can be performed using built-in methods or NumPy functions, (boolean) indexing, …
- When you have a function that cannot work on the full DataFrame/Series at once, it is better to use
apply()instead of iterating over the values. See the docs on function application. - If you need to do iterative manipulations on the values but performance is important, consider writing the inner loop with cython or numba. See the enhancing performance section for some examples of this approach.
Other answers to this question delve into greater depth on alternatives to iter* functions if you are interested to learn more.
From Stack Overflow: asked by Roman, answered by waitingkuo (CC BY-SA 4.0)
How do I select rows from a DataFrame based on column values?
To select rows whose column value equals a scalar,
some_value, use==:df.loc[df['column_name'] == some_value]To select rows whose column value is in an iterable,
some_values, useisin:df.loc[df['column_name'].isin(some_values)]Combine multiple conditions with
&:df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]Note the parentheses. Due to Python's operator precedence rules,
&binds more tightly than<=and>=. Thus, the parentheses in the last example are necessary. Without the parenthesesdf['column_name'] >= A & df['column_name'] <= Bis parsed as
df['column_name'] >= (A & df['column_name']) <= Bwhich results in a Truth value of a Series is ambiguous error.
To select rows whose column value does not equal
some_value, use!=:df.loc[df['column_name'] != some_value]The
isinreturns a boolean Series, so to select rows whose value is not insome_values, negate the boolean Series using~:df = df.loc[~df['column_name'].isin(some_values)] # .loc is not in-place replacementFor example,
import pandas as pd import numpy as np df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(), 'B': 'one one two three two two one three'.split(), 'C': np.arange(8), 'D': np.arange(8) * 2}) print(df) # A B C D # 0 foo one 0 0 # 1 bar one 1 2 # 2 foo two 2 4 # 3 bar three 3 6 # 4 foo two 4 8 # 5 bar two 5 10 # 6 foo one 6 12 # 7 foo three 7 14 print(df.loc[df['A'] == 'foo'])yields
A B C D 0 foo one 0 0 2 foo two 2 4 4 foo two 4 8 6 foo one 6 12 7 foo three 7 14If you have multiple values you want to include, put them in a list (or more generally, any iterable) and use
isin:print(df.loc[df['B'].isin(['one','three'])])yields
A B C D 0 foo one 0 0 1 bar one 1 2 3 bar three 3 6 6 foo one 6 12 7 foo three 7 14Note, however, that if you wish to do this many times, it is more efficient to make an index first, and then use
df.loc:df = df.set_index(['B']) print(df.loc['one'])yields
A C D B one foo 0 0 one bar 1 2 one foo 6 12or, to include multiple values from the index use
df.index.isin:df.loc[df.index.isin(['one','two'])]yields
A C D B one foo 0 0 one bar 1 2 two foo 2 4 two foo 4 8 two bar 5 10 one foo 6 12From Stack Overflow: asked by szli, answered by unutbu (CC BY-SA 4.0)
Renaming column names in Pandas
Just assign it to the
.columnsattribute:>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]}) >>> df $a $b 0 1 10 1 2 20 >>> df.columns = ['a', 'b'] >>> df a b 0 1 10 1 2 20From Stack Overflow: asked by user1504276, answered by eumiro (CC BY-SA 4.0)
Delete a column from a Pandas DataFrame
The best way to do this in Pandas is to use
drop:df = df.drop('column_name', axis=1)where
1is the axis number (0for rows and1for columns.)Or, the
drop()method acceptsindex/columnskeywords as an alternative to specifying the axis. So we can now just do:df = df.drop(columns=['column_nameA', 'column_nameB'])- This was introduced in v0.21.0 (October 27, 2017)
To delete the column without having to reassign
dfyou can do:df.drop('column_name', axis=1, inplace=True)Finally, to drop by column number instead of by column label, try this to delete, e.g. the 1st, 2nd and 4th columns:
df = df.drop(df.columns[[0, 1, 3]], axis=1) # df.columns is zero-based pd.IndexAlso working with "text" syntax for the columns:
df.drop(['column_nameA', 'column_nameB'], axis=1, inplace=True)From Stack Overflow: asked by John, answered by LondonRob (CC BY-SA 4.0)
How do I get the row count of a Pandas DataFrame?
For a dataframe
df, one can use any of the following:len(df.index)df.shape[0]df[df.columns[0]].count()(== number of non-NaN values in first column)
Code to reproduce the plot:
import numpy as np import pandas as pd import perfplot perfplot.save( "out.png", setup=lambda n: pd.DataFrame(np.arange(n * 3).reshape(n, 3)), n_range=[2**k for k in range(25)], kernels=[ lambda df: len(df.index), lambda df: df.shape[0], lambda df: df[df.columns[0]].count(), ], labels=["len(df.index)", "df.shape[0]", "df[df.columns[0]].count()"], xlabel="Number of rows", )From Stack Overflow: asked by yemu, answered by root (CC BY-SA 4.0)
Selecting multiple columns in a Pandas dataframe
The column names (which are strings) cannot be sliced in the manner you tried.
Here you have a couple of options. If you know from context which variables you want to slice out, you can just return a view of only those columns by passing a list into the
__getitem__syntax (the []'s).df1 = df[['a', 'b']]Alternatively, if it matters to index them numerically and not by their name (say your code should automatically do this without knowing the names of the first two columns) then you can do this instead:
df1 = df.iloc[:, 0:2] # Remember that Python does not slice inclusive of the ending index.Additionally, you should familiarize yourself with the idea of a view into a Pandas object vs. a copy of that object. The first of the above methods will return a new copy in memory of the desired sub-object (the desired slices).
Sometimes, however, there are indexing conventions in Pandas that don't do this and instead give you a new variable that just refers to the same chunk of memory as the sub-object or slice in the original object. This will happen with the second way of indexing, so you can modify it with the
.copy()method to get a regular copy. When this happens, changing what you think is the sliced object can sometimes alter the original object. Always good to be on the look out for this.df1 = df.iloc[0, 0:2].copy() # To avoid the case where changing df1 also changes dfTo use
iloc, you need to know the column positions (or indices). As the column positions may change, instead of hard-coding indices, you can useilocalong withget_locfunction ofcolumnsmethod of dataframe object to obtain column indices.{df.columns.get_loc(c): c for idx, c in enumerate(df.columns)}Now you can use this dictionary to access columns through names and using
iloc.From Stack Overflow: asked by user1234440, answered by ely (CC BY-SA 4.0)
How can I change the order of DataFrame columns?
One easy way would be to reassign the dataframe with a list of the columns, rearranged as needed.
This is what you have now:
In [6]: df Out[6]: 0 1 2 3 4 mean 0 0.445598 0.173835 0.343415 0.682252 0.582616 0.445543 1 0.881592 0.696942 0.702232 0.696724 0.373551 0.670208 2 0.662527 0.955193 0.131016 0.609548 0.804694 0.632596 3 0.260919 0.783467 0.593433 0.033426 0.512019 0.436653 4 0.131842 0.799367 0.182828 0.683330 0.019485 0.363371 5 0.498784 0.873495 0.383811 0.699289 0.480447 0.587165 6 0.388771 0.395757 0.745237 0.628406 0.784473 0.588529 7 0.147986 0.459451 0.310961 0.706435 0.100914 0.345149 8 0.394947 0.863494 0.585030 0.565944 0.356561 0.553195 9 0.689260 0.865243 0.136481 0.386582 0.730399 0.561593 In [7]: cols = df.columns.tolist() In [8]: cols Out[8]: [0L, 1L, 2L, 3L, 4L, 'mean']Rearrange
colsin any way you want. This is how I moved the last element to the first position:In [12]: cols = cols[-1:] + cols[:-1] In [13]: cols Out[13]: ['mean', 0L, 1L, 2L, 3L, 4L]Then reorder the dataframe like this:
In [16]: df = df[cols] # OR df = df.ix[:, cols] In [17]: df Out[17]: mean 0 1 2 3 4 0 0.445543 0.445598 0.173835 0.343415 0.682252 0.582616 1 0.670208 0.881592 0.696942 0.702232 0.696724 0.373551 2 0.632596 0.662527 0.955193 0.131016 0.609548 0.804694 3 0.436653 0.260919 0.783467 0.593433 0.033426 0.512019 4 0.363371 0.131842 0.799367 0.182828 0.683330 0.019485 5 0.587165 0.498784 0.873495 0.383811 0.699289 0.480447 6 0.588529 0.388771 0.395757 0.745237 0.628406 0.784473 7 0.345149 0.147986 0.459451 0.310961 0.706435 0.100914 8 0.553195 0.394947 0.863494 0.585030 0.565944 0.356561 9 0.561593 0.689260 0.865243 0.136481 0.386582 0.730399From Stack Overflow: asked by Timmie, answered by Aman (CC BY-SA 4.0)
Change column type in pandas
You have four main options for converting types in pandas:
to_numeric()- provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See alsoto_datetime()andto_timedelta().)astype()- convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to categorial types (very useful).infer_objects()- a utility method to convert object columns holding Python objects to a pandas type if possible.convert_dtypes()- convert DataFrame columns to the "best possible" dtype that supportspd.NA(pandas' object to indicate a missing value).
Read on for more detailed explanations and usage of each of these methods.
1.
to_numeric()The best way to convert one or more columns of a DataFrame to numeric values is to use
pandas.to_numeric().This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate.
Basic usage
The input to
to_numeric()is a Series or a single column of a DataFrame.>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values >>> s 0 8 1 6 2 7.5 3 3 4 0.9 dtype: object >>> pd.to_numeric(s) # convert everything to float values 0 8.0 1 6.0 2 7.5 3 3.0 4 0.9 dtype: float64As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:
# convert Series my_series = pd.to_numeric(my_series) # convert column "a" of a DataFrame df["a"] = pd.to_numeric(df["a"])You can also use it to convert multiple columns of a DataFrame via the
apply()method:# convert all columns of DataFrame df = df.apply(pd.to_numeric) # convert all columns of DataFrame # convert just columns "a" and "b" df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)As long as your values can all be converted, that's probably all you need.
Error handling
But what if some values can't be converted to a numeric type?
to_numeric()also takes anerrorskeyword argument that allows you to force non-numeric values to beNaN, or simply ignore columns containing these values.Here's an example using a Series of strings
swhich has the object dtype:>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10']) >>> s 0 1 1 2 2 4.7 3 pandas 4 10 dtype: objectRead the rest at the sourceFrom Stack Overflow: asked by user1642513, answered by Alex Riley (CC BY-SA 4.0)
How to deal with SettingWithCopyWarning in Pandas?
The
SettingWithCopyWarningwas created to flag potentially confusing "chained" assignments, such as the following, which does not always work as expected, particularly when the first selection returns a copy. [see GH5390 and GH5597 for background discussion.]df[df['A'] > 2]['B'] = new_val # new_val not set in dfThe warning offers a suggestion to rewrite as follows:
df.loc[df['A'] > 2, 'B'] = new_valHowever, this doesn't fit your usage, which is equivalent to:
df = df[df['A'] > 2] df['B'] = new_valWhile it's clear that you don't care about writes making it back to the original frame (since you are overwriting the reference to it), unfortunately this pattern cannot be differentiated from the first chained assignment example. Hence the (false positive) warning. The potential for false positives is addressed in the docs on indexing, if you'd like to read further. You can safely disable this new warning with the following assignment.
import pandas as pd pd.options.mode.chained_assignment = None # default='warn'Other Resources
- pandas User Guide: Indexing and selecting data
- Python Data Science Handbook: Data Indexing and Selection
- Real Python: SettingWithCopyWarning in Pandas: Views vs Copies
- Dataquest: SettingwithCopyWarning: How to Fix This Warning in Pandas
- Towards Data Science: Explaining the SettingWithCopyWarning in pandas
From Stack Overflow: asked by bigbug, answered by Garrett (CC BY-SA 4.0)
How to drop rows of Pandas DataFrame whose value in a certain column is NaN?
Don't drop, just take the rows where EPS is not NA:
df = df[df['EPS'].notna()]From Stack Overflow: asked by bigbug, answered by eumiro (CC BY-SA 4.0)
Get a list from Pandas DataFrame column headers
You can get the values as a list by doing:
list(my_dataframe.columns.values)Also you can simply use (as shown in Ed Chum's answer):
list(my_dataframe)From Stack Overflow: asked by natsuki_2002, answered by Simeon Visser (CC BY-SA 4.0)
Use a list of values to select rows from a Pandas dataframe
You can use the
isinmethod: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 3And to get the opposite use
~:In [4]: df[~df['A'].isin([3, 6])] Out[4]: A B 0 5 1 3 4 5From Stack Overflow: asked by zach, answered by Wouter Overmeire (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA13 questions