pandas DataFrame: get cells in column that are NaN, None, empty string/list, etc - python-3.x

there seems to be different methods to check if a cell is not set (NaN, by checking isnull) or whether it contains an empty string or list, but what is the most pythonic way to retrieve all cells that are NaN, None, empty string/list, etc. at the same time?
So far I got:
df = df[df['colname'].isnull() or df['colname'] == None or len(df['colname']) == 0]
Cheers!

One idea is chain Series.isna with compare lengths by Series.str.len:
df = pd.DataFrame({
'a':[None,np.nan,[],'','aa', 0],
})
m = df['a'].isna() | df['a'].str.len().eq(0)
print (m)
0 True
1 True
2 True
3 True
4 False
5 False
Name: a, dtype: bool

Related

how to get row index of a Pandas dataframe from a regex match

This question has been asked but I didn't find the answers complete. I have a dataframe that has unnecessary values in the first row and I want to find the row index of the animals:
df = pd.DataFrame({'a':['apple','rhino','gray','horn'],
'b':['honey','elephant', 'gray','trunk'],
'c':['cheese','lion', 'beige','mane']})
a b c
0 apple honey cheese
1 rhino elephant lion
2 gray gray beige
3 horn trunk mane
ani_pat = r"rhino|zebra|lion"
That means I want to find "1" - the row index that matches the pattern. One solution I saw here was like this; applying to my problem...
def findIdx(df, pattern):
return df.apply(lambda x: x.str.match(pattern, flags=re.IGNORECASE)).values.nonzero()
animal = findIdx(df, ani_pat)
print(animal)
(array([1, 1], dtype=int64), array([0, 2], dtype=int64))
That output is a tuple of NumPy arrays. I've got the basics of NumPy and Pandas, but I'm not sure what to do with this or how it relates to the df above.
I altered that lambda expression like this:
df.apply(lambda x: x.str.match(ani_pat, flags=re.IGNORECASE))
a b c
0 False False False
1 True False True
2 False False False
3 False False False
That makes a little more sense. but still trying to get the row index of the True values. How can I do that?
We can select from the filter the DataFrame index where there are rows that have any True value in them:
idx = df.index[
df.apply(lambda x: x.str.match(ani_pat, flags=re.IGNORECASE)).any(axis=1)
]
idx:
Int64Index([1], dtype='int64')
any on axis 1 will take the boolean DataFrame and reduce it to a single dimension based on the contents of the rows.
Before any:
a b c
0 False False False
1 True False True
2 False False False
3 False False False
After any:
0 False
1 True
2 False
3 False
dtype: bool
We can then use these boolean values as a mask for index (selecting indexes which have a True value):
Int64Index([1], dtype='int64')
If needed we can use tolist to get a list instead:
idx = df.index[
df.apply(lambda x: x.str.match(ani_pat, flags=re.IGNORECASE)).any(axis=1)
].tolist()
idx:
[1]

Delete dataframe rows based upon two dependent conditions

I have a fairly large dataframe (a few hundred columns) and I want to perform the following operation on it. I am using a toy dataframe below with a simple condition to illustrate what I need.
For every row:
Condition #1:
Check two of the columns for a value of zero (0). If this is true, keep the row
and move on to the next. If either column has a value of zero (0), the condition is True.
If Condition #1 is False (no zeros in either column 1 or 4)
Check all remaining columns in the row.
If any of the remaining columns has a value of zero, drop the row.
I would like the filtered dataframe returned as a new, separate dataframe.
My code so far:
# https://codereview.stackexchange.com/questions/185389/dropping-rows-from-a-pandas-dataframe-where-some-of-the-columns-have-value-0/185390
# https://thispointer.com/python-pandas-how-to-drop-rows-in-dataframe-by-conditions-on-column-values/
# https://stackoverflow.com/questions/29763620/how-to-select-all-columns-except-one-column-in-pandas
import pandas as pd
df = pd.DataFrame({'Col1': [7, 6, 0, 1, 8],
'Col2': [0.5, 0.5, 0, 0, 7],
'Col3': [0, 0, 3, 3, 6],
'Col4': [7, 0, 6, 4, 5]})
print(df)
print()
exclude = ['Col1', 'Col4']
all_but_1_and_4 = df[df.columns.difference(exclude)] # Filter out columns 1 and 4
print(all_but_1_and_4)
print()
def delete_rows(row):
if row['Col1'] == 0 or row['Col4'] == 0: # Is the value in either Col1 or Col4 zero(0)
skip = True # If it is, keep the row
if not skip: # If not, check the second condition
is_zero = all_but_1_and_4.apply(lambda x: 0 in x.values, axis=1).any() # Are any values in the remaining columns zero(0)
if is_zero: # If any of the remaining columns has a value of zero(0)
pass
# drop the row being analyzed # Drop the row.
new_df = df.apply(delete_rows, axis=1)
print(new_df)
I don't know how to actually drop the row if both of my conditions are met.
In my toy dataframe, rows 1, 2 and 4 should be kept, 0 and 3 dropped.
I do not want to manually check all columns for step 2 because there are several hundred. That is why I filtered using .difference().
What I will do
s1=df[exclude].eq(0).any(1)
s2=df[df.columns.difference(exclude)].eq(0).any(1)
~(~s1&s2) #s1 | ~s2
Out[97]:
0 False
1 True
2 True
3 False
4 True
dtype: bool
yourdf=df[s1 | ~s2].copy()
The WeNYoBen's answer is excellent, so I will only show mistakes in your code:
The condition in the following if statement will never fulfill:
skip = True # If it is, keep the row
if not skip: # If not, check the second condition
You probably wanted to unindent the following rows, i.e. something as
skip = True # If it is, keep the row
if not skip: # If not, check the second condition
which is the same as a simple else:, without the need of skip = True:
else: # If not, check the second condition
The condition in the following if statement will always fulfill, if at least one value in you whole table is zero (so not only in the current row, as you supposed):
is_zero = all_but_1_and_4.apply(lambda x: 0 in x.values, axis=1).any() # Are any values in the remaining columns zero(0)
if is_zero: # If any of the remaining columns has a value of zero(0)
because all_but_1_and_4.apply(lambda x: 0 in x.values, axis=1) is a series of True / False values - one for every row in the all_but_1_and_4 table. So after applying the .any() method to it you receive what I said.
Note:
Your approach is not bad, you may add a variable dropThisRow in your function, set it to True or False depending on conditions, and return it.
Then you may use your function to make the True / False series and use it for creating your target table:
dropRows = df.apply(delete_rows, axis=1) # True/False for dropping/keeping - for every row
new_df = df[~dropRows] # Select only rows with False

Looking for NaN values in a specific column in df [duplicate]

Now I know how to check the dataframe for specific values across multiple columns. However, I cant seem to work out how to carry out an if statement based on a boolean response.
For example:
Walk directories using os.walk and read in a specific file into a dataframe.
for root, dirs, files in os.walk(main):
filters = '*specificfile.csv'
for filename in fnmatch.filter(files, filters):
df = pd.read_csv(os.path.join(root, filename),error_bad_lines=False)
Now checking that dataframe across multiple columns. The first value being the column name (column1), the next value is the specific value I am looking for in that column(banana). I am then checking another column (column2) for a specific value (green). If both of these are true I want to carry out a specific task. However if it is false I want to do something else.
so something like:
if (df['column1']=='banana') & (df['colour']=='green'):
do something
else:
do something
If you want to check if any row of the DataFrame meets your conditions you can use .any() along with your condition . Example -
if ((df['column1']=='banana') & (df['colour']=='green')).any():
Example -
In [16]: df
Out[16]:
A B
0 1 2
1 3 4
2 5 6
In [17]: ((df['A']==1) & (df['B'] == 2)).any()
Out[17]: True
This is because your condition - ((df['column1']=='banana') & (df['colour']=='green')) - returns a Series of True/False values.
This is because in pandas when you compare a series against a scalar value, it returns the result of comparing each row of that series against the scalar value and the result is a series of True/False values indicating the result of comparison of that row with the scalar value. Example -
In [19]: (df['A']==1)
Out[19]:
0 True
1 False
2 False
Name: A, dtype: bool
In [20]: (df['B'] == 2)
Out[20]:
0 True
1 False
2 False
Name: B, dtype: bool
And the & does row-wise and for the two series. Example -
In [18]: ((df['A']==1) & (df['B'] == 2))
Out[18]:
0 True
1 False
2 False
dtype: bool
Now to check if any of the values from this series is True, you can use .any() , to check if all the values in the series are True, you can use .all() .

replace values in pandas based on other two column

I have problem with replacement values in a column conditional other two columns.
For example we have three columns. A, B, and C
Columns A and B are both booleans, containing True and False, and column C contains three values: "Payroll", "Social", and "Other".
When in columns A and B are True in column C we have value "Payroll".
I want to change values in column C where both column A and B are True.
I tried following code: but gives me this error "'NoneType' object has no attribute 'where'":
data1.replace({'C' : { 'Payroll', 'Social'}},inplace=True).where((data1['A'] == True) & (data1['B'] == True))
but gives me this error "'NoneType' object has no attribute 'where'":
What can be done to this problem?
I think you need all for check if all Trues per rows and then assign output by filtered DataFrame by boolean mask:
data1 = pd.DataFrame({
'C': ['Payroll','Other','Payroll','Social'],
'A': [True, True, True, False],
'B':[False, True, True, False]
})
print (data1)
A B C
0 True False Payroll
1 True True Other
2 True True Payroll
3 False False Social
m = data1[['A', 'B']].all(axis=1)
#same output as
#m = data1['A'] & data1['B']
print (m)
0 False
1 True
2 True
3 False
dtype: bool
print (data1[m])
A B C
1 True True Other
2 True True Payroll
data1[m] = data1[m].replace({'C' : { 'Payroll':'Social'}})
print (data1)
A B C
0 True False Payroll
1 True True Other
2 True True Social
3 False False Social
Well you can use apply function to do this
def change_value(dataframe):
for index, row in df.iterrows():
if row['A'] == row['B'] == True:
row['C'] = # Change to whatever value you want
else:
row ['C'] = # Change how ever you want

Pandas rolling idmax for True/False rows?

I'm keeping score in a True/False column when determining whether some signal is below the background level, so for example
sig bg is_below
5 3 False
5 3 False
5 3 False
2 3 True # "False positive"
4 3 False
4 3 False
0 3 True # Signal is dead and not returning from this point onwards
0 3 True
0 3 True
0 3 True
0 3 True
But as I've shown, noise may sometimes generate "false positives", and smoothing the data doesn't get rid of some big spikes, without oversmoothing smaller data. I'm sure there's a proper mathematical way, but perhaps that would be overkill in work and computational efficiency.
Instead, how do I determine the index of the first True where True appears e.g. 3 times in a row?
Okay, so I just remembered that True/False could just as easily be interpreted as 1/0, and so a rolling median, e.g.
scipy.signal.medfilt(df["is_below"], kernel_size = 5).argmax()
Would return the index of the first time encountering [False, False, True, True, True], as the median of [0, 0, 1, 1, 1] is the smallest window that returns 3 True in a row.
I don't know if there is an even better way, but given that I have 100s of datapoints in my timeseries, the returned argmax index is accurate enough for my application.
If your data is in a pandas dataframe (say called df), you can do it by creating a boolean variable b which is True at each row only when the row and previous two rows are True in df.is_below.
b = ((df.is_below == True) & (df.is_below.shift(-1) == True) & (df.is_below.shift(-2) == True))
Here, df.is_below.shift(-1) shifts the whole dataframe back by 1, so we are looking at the previous row (and similarly for shift(-2) to look at the row before the previous row).
Full code below:
import pandas as pd
# Create dataframe
df = pd.DataFrame()
sig = [5, 5, 5, 2, 4, 4, 0, 0, 0, 0, 0]
df['sig'] = sig
df['bg'] = [3] * len(sig)
df['is_below'] = df.sig < df.bg
# Find index of first consecutive three True in df.is_below
b = ((df.is_below == True) & (df.is_below.shift(-1) == True) & (df.is_below.shift(-2) == True))
idx = df.index[b][0] # first index where three Trues are in a row

Resources