Pandas deleting row with df.drop doesn't work
While dropping new DataFrame returns. If you want to apply changes to the current DataFrame you have to specify inplace
parameter.
Option 1
Assigning back to df
-
df = df.drop(790)
Option 2
Inplace argument -
df.drop(790, inplace=True)
Deleting DataFrame row in Pandas based on column value
If I'm understanding correctly, it should be as simple as:
df = df[df.line_race != 0]
dropping column using pandas-drop()-function not working
So there are 2 problems:
First need change separator to tab
, because read_csv
have default sep=','
as commented @cᴏʟᴅsᴘᴇᴇᴅ:
df = read_csv('USrealGDPGrowthPred_Quarterly.txt', header=0, sep='\t')
Or use read_table
with default sep='\t'
:
df = df.read_table('USrealGDPGrowthPred_Quarterly.txt', header=0)
And then assign output back or use inplace=True
in drop
:
dataset = dataset.drop('DATE', axis=1)
Or:
dataset.drop('DATE', axis=1, inplace=True)`
dropping rows from dataframe based on a not in condition
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
How to delete any row for which a corresponding column has a negative value using Pandas?
You can drop rows for which in a specific column the value is negative using pandas.DataFrame.drop
as follows:
import pandas as pd
df = pd.DataFrame({
'colA': [-1, 2, 3, 4, None],
'colB': [True, True, False, False, True],
})
df = df.drop(df.index[df['colA'] < 0])
Output:
>>> df
colA colB
1 2.0 True
2 3.0 False
3 4.0 False
4 NaN True
Related Topics
Matplotlib: How to Prevent X-Axis Labels from Overlapping
How to Call Python Functions Dynamically
Constructing a Co-Occurrence Matrix in Python Pandas
Pip Ignores Dependency_Links in Setup.Py
General Unicode/Utf-8 Support for CSV Files in Python 2.6
Optimizing Database Queries in Django Rest Framework
Why Doesn't Print Work in a Lambda
Get Last Result in Interactive Python Shell
How to Sort and Remove Duplicates from Python List
How to Multiply Each Element in a List by a Number
How Come a File Doesn't Get Written Until I Stop the Program
How to Create an Incrementing Filename in Python