將Pandas DataFrame 字串條目分解(分割)為單獨的行
在Pandas 中,常見的要求是將逗號分隔的值拆分為文字字串列並為每個條目建立一個新行。這可以透過各種方法來實現。
使用Series.explode() 或DataFrame.explode()
對於Pandas 版本0.25.0 及更高版本,Series. explode() 和DataFrame.explode () 方法提供了一種類似CSV的爆炸方式列:
對於單列:
df.explode('column_name')
對於多列:
df.explode(['column1', 'column2']) # Pandas 1.3.0+
通用向量化函數
一種更通用的向量化方法下面提供了適用於普通列和列表列的方法:
def explode(df, lst_cols, fill_value='', preserve_index=False): # Convert CSV string columns to list columns for col in lst_cols: df[col] = df[col].str.split(',') # Extract all non-list columns idx_cols = df.columns.difference(lst_cols) # Calculate list lengths lens = df[lst_cols[0]].str.len() # Create exploded DataFrame result = (pd.DataFrame({ col: np.repeat(df[col].values, lens) for col in idx_cols }, index=np.repeat(df.index.values, lens)) .assign(**{col: np.concatenate(df.loc[lens>0, col].values) for col in lst_cols})) # Handle empty list rows if (lens == 0).any(): result = result.append(df.loc[lens==0, idx_cols], sort=False).fillna(fill_value) # Revert index order and reset index if requested result = result.sort_index() if not preserve_index: result = result.reset_index(drop=True) return result
應用程式
CSV欄位:
df['var1'] = df['var1'].str.split(',')
多個清單欄位:
explode(df, ['num', 'text'], fill_value='')
以上是如何將 Pandas DataFrame 字串條目分解(拆分)為單獨的行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

ArraySareBetterForlement-WiseOperationsDuetofasterAccessCessCessCessCessCessCessCessAndOptimizedImplementations.1)ArrayshaveContiguucuulmemoryfordirectAccesscess.2)列出sareflexible butslible butslowerduetynemicizing.3)

在NumPy中进行整个数组的数学运算可以通过向量化操作高效实现。1)使用简单运算符如加法(arr 2)可对数组进行运算。2)NumPy使用C语言底层库,提升了运算速度。3)可以进行乘法、除法、指数等复杂运算。4)需注意广播操作,确保数组形状兼容。5)使用NumPy函数如np.sum()能显著提高性能。

在Python中,向列表插入元素有兩種主要方法:1)使用insert(index,value)方法,可以在指定索引處插入元素,但在大列表開頭插入效率低;2)使用append(value)方法,在列表末尾添加元素,效率高。對於大列表,建議使用append()或考慮使用deque或NumPy數組來優化性能。

tomakeapythonscriptexecutableonbothunixandwindows:1)addashebangline(#!/usr/usr/bin/envpython3)Andusechmod xtomakeitexecutableonix.2)onWindows,確保pytythonisinstalledandassionstalledandassociatedwith.pyfiles,oruseabatchfile(runun.batchfile(runitter)(rugitty.batt)

當遇到“commandnotfound”錯誤時,應檢查以下幾點:1.確認腳本存在且路徑正確;2.檢查文件權限,必要時使用chmod添加執行權限;3.確保腳本解釋器已安裝並在PATH中;4.驗證腳本開頭的shebang行是否正確。這樣做可以有效解決腳本運行問題,確保編碼過程順利進行。

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


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

禪工作室 13.0.1
強大的PHP整合開發環境

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能