簡體   English   中英

將一維 Numpy 數組作為一行添加到 DataFrame

[英]Add A 1-D Numpy Array to DataFrame as a Row

是否有一個 function 可以讓您有效地將 append 一個 NumPy 數組直接轉換為 ZBA834Z9C112A9A3EB87845

變量:

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])

我如何直接 append arrdf的末尾來得到這個?

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

我試過使用df.append(arr)但它不接受 NumPy arrays。 我可以將 NumPy 數組轉換為 DataFrame 然后 append 它,但我認為這將非常低效,尤其是在數百萬次迭代中。 有沒有更有效的方法來做到這一點?

@BalrogOfMoira 真的比簡單地創建 dataframe 到 append 更快嗎?

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

否則@Wonton,您可以簡單地連接 arrays 然后寫入數據幀,該數據幀可以附加到原始數據幀。

這將起作用:

df.append(pd.DataFrame(arr).T)

@rafaelc 注釋只有在您的 Pandas DataFrame 的索引從 0 到 len(df)-1 時才有效,因此它不是一般的解決方法,它很容易在您的代碼中產生無聲的錯誤。

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 function 不支持就地修改。

我希望它有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM