Reputation: 7421
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
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
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
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