是否有一个函数可以让您有效地将 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/