Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pandas where

# replaces values with other where condition is False
DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False)

import pandas as pd 
df = pd.DataFrame({'values':[1,2,3,4]})

df.where(df['values'] % 2 == 0, -1) # output : [-1, 2, -3, 4]
Comment

Python | Pandas DataFrame.where()

# importing pandas package
import pandas as pd
  
# making data frame from csv file
data = pd.read_csv("cff.csv")
  
# sorting dataframe
data.sort_values("Team", inplace = True)
  
# making boolean series for a team name
filter = data["Team"]=="cff"
  
# filtering data
data.where(filter, inplace = True)
  
# display
data
Comment

pandas df where

df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
>>> df
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9
>>> m = df % 3 == 0
>>> df.where(m, -df)
   A  B
0  0 -1
1 -2  3
2 -4 -5
3  6 -7
4 -8  9
>>> df.where(m, -df) == np.where(m, df, -df)
      A     B
0  True  True
1  True  True
2  True  True
3  True  True
4  True  True
>>> df.where(m, -df) == df.mask(~m, -df)
      A     B
0  True  True
1  True  True
2  True  True
3  True  True
4  True  True
Comment

pandas where

In [20]: df
Out[20]:
   A  B  C
0  1  2  1
1  2  3  0
2  3  4  0
3  4  5  1

# Note that df.C is a mask
# Note that this is np.where, not df.where. That is different.
In [21]: df['D'] = np.where(df.C, df.A, df.B)

In [22]: df
Out[22]:
   A  B  C  D
0  1  2  1  1
1  2  3  0  3
2  3  4  0  4
3  4  5  1  4
Comment

PREVIOUS NEXT
Code Example
Python :: class indexing 
Python :: .lift tkinter 
Python :: .format python 3 
Python :: numpy array deepcopy 
Python :: 231a codeforces solution in python 
Python :: unsplash python 
Python :: flask form 
Python :: python get input 
Python :: initialize np array 
Python :: adfuller test in python 
Python :: python if true 
Python :: turtle graphics documentation|pensize 
Python :: pandas to python datetime 
Python :: how to install ffmpeg_streaming in python 
Python :: tables in python 
Python :: python change dictionary key 
Python :: Your WhiteNoise configuration is incompatible with WhiteNoise v4.0 
Python :: python convert b string to dict 
Python :: Customizable TKinter Buttons Python 
Python :: matrix diagonal sum leetcode in Python 
Python :: python factor number 
Python :: argparse accept only few options 
Python :: django login url 
Python :: python command line keyword arguments 
Python :: EOFError: EOF when reading a line 
Python :: write string python 
Python :: dict in dict in python 
Python :: how to negate a boolean python 
Python :: python insert sorted 
Python :: pandas how to drop rows with extreme values in a single column 
ADD CONTENT
Topic
Content
Source link
Name
8+6 =