将一维Numpy数组作为行添加到DataFrame [英] Add A 1-D Numpy Array to DataFrame as a Row

查看:224
本文介绍了将一维Numpy数组作为行添加到DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a function which allows you to efficiently append a NumPy array directly to a 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 的末尾以获取此信息?

How do I directly append arr to the end of dfto get this?

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

我尝试使用 df.append(arr),但是它不接受NumPy数组.我可以将NumPy数组转换为DataFrame然后追加它,但是我认为这样的效率非常低,尤其是经过数百万次迭代后.有更有效的方法吗?

I've tried using df.append(arr) but it doesn't accept NumPy arrays. I could convert the NumPy array into a DataFrame then append it, but I think that would be very inefficient, especially over millions of iterations. Is there a more efficient way to do it?

推荐答案

@rafaelc注释仅在将Pandas DataFrame的索引从0索引为len(df)-1时才有效,因此这不是一般的解决方法,并且可以轻松实现在您的代码中产生一个无声的错误.

@rafaelc comment can work only if your Pandas DataFrame is indexed from 0 to len(df)-1, so it is not a general workaround and it can easily produce a silent bug in your code.

如果您确定Numpy数组具有与Pandas DataFrame相同的列,则可以尝试使用 append 函数和dict理解,如下所示:

If you are sure that your Numpy array has the same columns of your Pandas DataFrame you could try using the append function with a dict comprehension as follows:

data_to_append = {}
for i in range(len(df.columns)):
    data_to_append[df.columns[i]] = arr[i]
df = df.append(data_to_append, ignore_index = True)

您需要重新分配DataFrame,因为 append 功能不支持就地修改.

You need to reassign the DataFrame because append function does not support in-place modification.

希望对您有帮助.

这篇关于将一维Numpy数组作为行添加到DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆