python中向二維數(shù)組中添加整行或者增列元素問題
更新時間:2023年01月31日 10:47:49 作者:ShaoDu
這篇文章主要介紹了python中向二維數(shù)組中添加整行或者增列元素問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
向二維數(shù)組中添加整行或者增列元素
1、numpy中empty方法可以創(chuàng)建一個二維數(shù)組
x=np.empty(shape=[0,4],dtype=int)
創(chuàng)建了一個空的四列的二維數(shù)組
2、添加需要的元素
x=np.append(x,[[1,2,3,4]],axis=0)#添加整行元素,axis=1添加整列元素
如何在數(shù)組中添加一行數(shù)據(jù)
python在數(shù)組中添加一行數(shù)據(jù)的方法:
1、直接插入一行:
import pandas as pd from pandas import DataFrame?? df3=DataFrame(np.arange(16).reshape((4,4)),index=['a','b','c','d'],columns=['one','two','three','four'])? ?? # 新插入的行一定要加 index,不然會報錯 df3.loc['new'] = ['a','a','a','a'] ?? # 運行結果為?? ? ? one two three ? four a ? 0 ? 1 ? 2 ? 3 b ? 4 ? 5 ? 6 ? 7 c ? 8 ? 9 ? 10 ?11 d ? 12 ?13 ?14 ?15 new a ? a ? a ? a
2、新建一個同樣的 dataframe, 然后合并兩個dataframe
df4 = pd.DataFrame([6,6,6,6]).T # 修改df4的column和df3的一致 df4.columns = df3.columns # 把兩個dataframe合并,需要設置 ignore_index=True df_new = pd.concat([df3,df4],ignore_index=True) ?? # 運行結果?? ? ? one two three ? four 0 ? 0 ? 1 ? 2 ? 3 1 ? 4 ? 5 ? 6 ? 7 2 ? 8 ? 9 ? 10 ?11 3 ? 12 ?13 ?14 ?15 4 ? a ? a ? a ? a 5 ? 6 ? 6 ? 6 ? 6
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Linux中安裝Python的交互式解釋器IPython的教程
IPython是一種基于Python的Shell,由于有了Python編程語言的支撐,而比一般的Shell更加強大.下面就來看一下Linux中安裝Python的交互式解釋器IPython的教程2016-06-06

