首页 > 解决方案 > 使用熊猫在数据框中添加一个空行:标准最佳性能

问题描述

# dataframe is onedf
 temp_false_list = []
for xray in range(onedf.shape[1]):
       temp_false_list.append(np.nan)
onedf.loc[len(onedf)] = temp_false_list # this line takes 90% of time 


标签: pythonpandas

解决方案


pandas 中的追加操作成本很高。您可以做的是将数据框转换为字典列表,然后将 temp 附加到字典的 python 列表中。处理后,将字典列表转换回数据框。

例如,假设我有一个这样的数据框 onedf。-

|   | product  | old_price | new_price | final_price |
|---|----------|-----------|-----------|-------------|
| 0 | product1 | 10        | 20.0      | 10.0        |
| 1 | product2 | 20        | 10.0      | -10.0       |
| 2 | product3 | 30        | NaN       | NaN         |
| 3 | product4 | 40        | NaN       | NaN         |

现在,您想将行附加到其中,因此首先将其转换为字典列表-

dict1 = onedf.to_dict(orient='records')

这将给出这样的输出 -

[{'product': 'product1',
  'old_price': 10,
  'new_price': 20.0,
  'final_price': 10.0},
 {'product': 'product2',
  'old_price': 20,
  'new_price': 10.0,
  'final_price': -10.0},
 {'product': 'product3',
  'old_price': 30,
  'new_price': nan,
  'final_price': nan},
 {'product': 'product4',
  'old_price': 40,
  'new_price': nan,
  'final_price': nan}]

现在,只需创建一个匹配相同格式的空字典并追加。做起来会快很多。


import numpy as np
temp_false_list = [np.nan for _ in range(4)]
temp_dict = dict(zip(onedf.columns.values,temp_false_list))
# {'product': nan, 'old_price': nan, 'new_price': nan, 'final_price': nan}

将它附加到我们之前创建的 dict -

dict1.append(temp_dict)

最后,将 dict1 转换回数据帧。

onedf_new = pd.DataFrame(dict1)

推荐阅读