【发布时间】:2018-06-01 16:42:34
【问题描述】:
我想对大约 400k 行、4 列的 Dataframe 进行排序,用 if 语句取出大约一半:
for a in range (0, howmanytimestorunthrough):
if ('Primary' not in DataFrameexample[a]):
#take out row
到目前为止,我一直在测试以下 4 个之一:
newdf.append(emptyline,)
nefdf.at[b,'column1'] = DataFrameexample.at[a,'column1']
nefdf.at[b,'column2'] = DataFrameexample.at[a,'column2']
nefdf.at[b,'column3'] = DataFrameexample.at[a,'column3']
nefdf.at[b,'column4'] = DataFrameexample.at[a,'column4']
b = b + 1
或与 .loc 相同
newdf.append(emptyline,)
nefdf.loc[b,:] = DataFrameexample.loc[a,:]
b = b + 1
或将 if (not in) 更改为 if (in) 并使用:
DataFrameexample = DataFrameexample.drop([k])
或尝试将空行设置为具有值,然后附加它:
notemptyline = pd.Series(DataFrameexample.loc[a,:].values, index = ['column1', 'column2', ...)
newdf.append(notemptyline, ignore_index=True)
因此,从我迄今为止的测试来看,它们似乎在少数行(2000 行)上都可以正常工作,但是一旦我开始获得更多行,它们所需的时间就会成倍增加。 .at 似乎比 .loc 快一点,即使我需要它运行 4 次,但仍然变慢(行数的 10 倍,花费的时间超过 10 倍)。 .drop 我认为每次都尝试复制数据帧,所以真的不起作用吗?我似乎无法让 .append(notemptyline) 正常工作,它只是一遍又一遍地替换索引 0。
我知道必须有一种有效的方法来做到这一点,但我似乎无法做到这一点。有什么帮助吗?
【问题讨论】:
标签: python performance pandas dataframe