cardamom
cardamom

Reputation: 7421

truncate all rows from a pandas dataframe

I need to test that some code works if a dataframe has no rows in it. In SQL you can clean all the rows out of a table with the truncate command. I found the Pandas truncate command, but can't get rid of the very last row. I did this:

df.truncate(after=0, before=0)

..but it left the 0th row. Any ideas?

Upvotes: 7

Views: 11566

Answers (3)

jezrael
jezrael

Reputation: 862591

Use drop by all index values:

df1 = df.drop(df.index)

Or DataFrame constructor with columns parameter only:

df1 = pd.DataFrame(columns=df.columns)

Sample:

df = pd.DataFrame({'a':list('ab'), 'b':range(2)})

df1 = df.drop(df.index)
print (df1)
Empty DataFrame
Columns: [a, b]
Index: []

Upvotes: 9

BENY
BENY

Reputation: 323226

Your truncate working on my side

df.truncate(before=-1, after=-1)
Out[835]: 
Empty DataFrame
Columns: [A, B, C]
Index: []

Upvotes: 6

The Data Scientician
The Data Scientician

Reputation: 491

You can use df.head(0)

In [3]: df = pd.DataFrame([{'foo': 1, 'bar': 2}, {'foo': 3, 'bar': 4}])

In [4]: df
Out[4]: 
   bar  foo
0    2    1
1    4    3

In [5]: df.head(0)
Out[5]: 
Empty DataFrame
Columns: [bar, foo]
Index: []

Upvotes: 13

Related Questions