在單一分配中向 Pandas DataFrame 新增多個欄位
在 Pandas 中,可以透過多種方式同時新增多個欄位。一種方法是單獨為每一列分配值,但這對於多個列來說可能會變得乏味。更有效的方法是一步新增列。
乍一看,使用列列表語法將列表或數組分配給多個新列(例如df[['new1', 'new2' ]] = [標量,標量]) 可能看起來很直觀。但是,此分配僅適用於現有列。
要在單一操作中新增列並指派數值,您可以使用多種方法:
1.迭代器解包:
<code class="python">df['new1'], df['new2'], df['new3'] = np.nan, 'dogs', 3</code>
此方法迭代地將值指派給每個新欄位。
2. DataFrame 擴充:
<code class="python">df[['new1', 'new2', 'new3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)</code>
此方法建立一個具有與原始DataFrame 索引相符的單行的DataFrame,然後使用Pandas 的concat 函數將新列合併到原始列。
3.暫時 DataFrame 連線:
<code class="python">df = pd.concat([df, pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index, columns=['new1', 'new2', 'new3'])], axis=1)</code>
此方法使用新欄位和值建立一個暫存 DataFrame,然後將其與原始 DataFrame 連線。
4.字典賦值:
<code class="python">df = df.join(pd.DataFrame({'new1': np.nan, 'new2': 'dogs', 'new3': 3}, index=df.index))</code>
此方法使用字典建立一個暫存 DataFrame,然後與原始 DataFrame 連接。
5. .assign() 方法:
<code class="python">df = df.assign(new1=np.nan, new2='dogs', new3=3)</code>
.assign() 方法允許一次分配多列。
6.建立列並指派值:
<code class="python">new_cols = ['new1', 'new2', 'new3'] new_vals = [np.nan, 'dogs', 3] df = df.reindex(columns=df.columns.tolist() + new_cols) df[new_cols] = new_vals</code>
此技術建立空列並分別分配值。
多個單獨分配:
<code class="python">df['new1'] = np.nan df['new2'] = 'dogs' df['new3'] = 3</code>
雖然不如其他方法高效,但單獨分配很簡單,並且可用於少量新列。
最佳選擇取決於特定要求和性能考慮。對於同時新增多個列,DataFrame 擴充或暫存 DataFrame 連接方法提供了簡潔且有效率的解決方案。
以上是如何在一次分配中有效地將多列新增至 Pandas DataFrame ?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

ArraySareAryallyMoremory-Moremory-forigationDataDatueTotheIrfixed-SizenatureAntatureAntatureAndirectMemoryAccess.1)arraysStorelelementsInAcontiguxufulock,ReducingOveringOverheadHeadefromenterSormetormetAdata.2)列表,通常

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python列表可以存儲不同類型的數據。示例列表包含整數、字符串、浮點數、布爾值、嵌套列表和字典。列表的靈活性在數據處理和原型設計中很有價值,但需謹慎使用以確保代碼的可讀性和可維護性。

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

theSostCommonlyusedModuleForCreatingArraysInpyThonisnumpy.1)NumpyProvidEseffitedToolsForarrayOperations,Idealfornumericaldata.2)arraysCanbeCreatedDusingsnp.Array()for1dand2Structures.3)

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。1)在金融中,使用内存映射文件和NumPy库可显著提升数据处理速度。2)科研领域,HDF5文件优化数据存储和检索。3)医疗中,数据库优化技术如索引和分区提高数据查询性能。4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显著提升系统性能和可扩展性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

記事本++7.3.1
好用且免費的程式碼編輯器

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!