python - 将一维 Numpy 数组作为行添加到 DataFrame

标签 python arrays pandas numpy dataframe

是否有一个函数可以让您有效地将 NumPy 数组直接附加到 DataFrame?

变量:

df = pd.DataFrame(columns=['col1', 'col2', 'col3'])

Out[1]: +------+------+------+
        | Col1 | Col2 | Col3 |
        +------+------+------+
        |      |      |      |
        +------+------+------+


arr = np.empty(3)

# array is populated with values. Random numbers are chosen in this example,
#    but in my program, the numbers are not arbitrary.
arr[0] = 756
arr[1] = 123
arr[2] = 452

Out[2]: array([756, 123, 452])

如何直接将 arr 附加到 df 的末尾来获取此值?

+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
|  756 |  123 |  452 |
+------+------+------+

我尝试过使用 df.append(arr) ,但它不接受 NumPy 数组。我可以将 NumPy 数组转换为 DataFrame,然后附加它,但我认为这效率非常低,尤其是在数百万次迭代中。有没有更有效的方法来做到这一点?

最佳答案

@BalrogOfMoira 这真的比简单地创建要附加的数据帧更快吗?

df.append(pd.DataFrame(arr.reshape(1,-1), columns=list(df)), ignore_index=True)

否则@Wonton,您可以简单地连接数组,然后写入数据帧,该数据帧可以附加到原始数据帧。

关于python - 将一维 Numpy 数组作为行添加到 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58292901/

相关文章:

python - python中用于列表操作的plus和append有什么区别?

python - 如何在处理程序中对 Tornado 处理程序进行基准测试?

arrays - 按特定顺序组合两个数组

php - 如何在php中将具有相同键的数组合并为一个

python - Positional ,关键字,可选和必需参数之间的区别?

python - 使用 Python 列出 Google Cloud Storage 存储桶

java - 将单个字符重复到字符数组。设置数组的长度以匹配字符串所需的长度

python - 用 pandas 读取加密的 excel

python - Pandas MultiIndex groupby 保留索引级别

python - 如何用 pandas 将大表保存为图像