python - 使用熊猫在数据框中添加一个空行:标准最佳性能
问题描述
- 要求:向数据框添加添加空行
- 约束:性能
# 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
解决方案
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)
推荐阅读
- javascript - 如何通过 Angular 中的路由在 Cloud Functions 中执行对 Cloud Firestore 的添加?
- ios - 在 UITableView 中至少选择一行
- ios - 从 AppDelegate 调用一个函数并使用该函数执行 segue
- wordpress - 更改“/shop”档案中的程序默认产品变体图像-Woocommerce
- r - 为什么我的 dplyr 语句会创建额外的行?
- c# - 使用通用扩展方法将实体映射到视图模型
- vba - VBA更改文件夹中所有文件的名称
- c# - 实体框架延迟加载总和子表慢
- c# - 使用锁来排队任务是一个好习惯吗?
- c# - 查找数据库中是否存在 300K 记录的最快方法