删除pandas数据帧中的所有数据

use*_*044 26 python python-2.7 pandas

我想将所有数据丢弃在pandas数据框中,但我得到了TypeError: drop() takes at least 2 arguments (3 given).我本质上想要一个只有我的列标题的空白数据框.

import pandas as pd

web_stats = {'Day': [1, 2, 3, 4, 2, 6],
             'Visitors': [43, 43, 34, 23, 43, 23],
             'Bounce_Rate': [3, 2, 4, 3, 5, 5]}
df = pd.DataFrame(web_stats)

df.drop(axis=0, inplace=True)
print df
Run Code Online (Sandbox Code Playgroud)

ayh*_*han 54

您需要传递要删除的标签.

df.drop(df.index, inplace=True)
Run Code Online (Sandbox Code Playgroud)

默认情况下,它会运行axis=0.

你可以实现同样的目标

df.iloc[0:0]
Run Code Online (Sandbox Code Playgroud)

这更有效率.


tom*_*tom 11

我的最爱:

df = df.iloc[0:0]
Run Code Online (Sandbox Code Playgroud)

但要注意df.index.max()将是nan.要添加我使用的项目:

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data
Run Code Online (Sandbox Code Playgroud)


小智 11

用类似的东西覆盖数据框

import pandas as pd

df = pd.DataFrame(None)
Run Code Online (Sandbox Code Playgroud)

或者如果您想将列保留在适当的位置

df = pd.DataFrame(columns=df.columns)
Run Code Online (Sandbox Code Playgroud)


小智 5

我最喜欢的方式是:

df = df[0:0] 
Run Code Online (Sandbox Code Playgroud)