將Pandas 數據框字符串條目拆分(分解)到單獨的行
問題:
操作Pandas 資料框包含一列逗號分隔值,目標是拆分每個值將CSV欄位分成單獨的行,保留原始資料結構。
解決方案:
推薦的解決方案是利用Pandas Series.explode() 或DataFrame.explode( ) 方法,在Pandas 0.25.0 中引入,並在Pandas 1.3.0 中增強以支援多列爆炸。
要爆炸單一列,請使用Series.explode():
df.explode('column_name')
對於多列,請使用DataFrame.explode():
df.explode(['column1', 'column2'])
範例:
df = pd.DataFrame({ 'A': [[0, 1, 2], 'foo', [], [3, 4]], 'B': 1, 'C': [['a', 'b', 'c'], np.nan, [], ['d', 'e']] }) df.explode('A')
輸出:
A B C 0 0 1 [a, b, c] 0 1 1 [a, b, c] 0 2 1 [a, b, c] 1 foo 1 NaN 2 NaN 1 [] 3 3 1 [d, e] 3 4 1 [d, e]
適用於多個普通列和列表列的更通用方法,考慮以下函數:
def explode(df, lst_cols, fill_value='', preserve_index=False): # Ensure `lst_cols` is list-alike if lst_cols and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series)): lst_cols = [lst_cols] # Calculate lengths of lists lens = df[lst_cols[0]].str.len() # Preserve original index values idx = np.repeat(df.index.values, lens) # Create an "exploded" DataFrame res = (pd.DataFrame({ col:np.repeat(df[col].values, lens) for col in df.columns.difference(lst_cols) }, index=idx) .assign(**{col:np.concatenate(df.loc[lens>0, col].values) for col in lst_cols})) # Append rows with empty lists if (lens == 0).any(): res = (res.append(df.loc[lens==0, df.columns.difference(lst_cols)], sort=False) .fillna(fill_value)) # Revert to original index order and reset if requested res = res.sort_index() if not preserve_index: res = res.reset_index(drop=True) return res
霹靂a 的範例類似 CSV 的欄位:
df = pd.DataFrame({ 'var1': 'a,b,c d,e,f,x,y'.split(), 'var2': [1, 2] }) explode(df.assign(var1=df.var1.str.split(',')), 'var1')
輸出:
var1 var2 0 a 1 1 b 1 2 c 1 3 d 2 4 e 2 5 f 2 6 x 2 7 y 2
以上是如何將 Pandas DataFrame 中的逗號分隔值拆分為單獨的行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的關鍵特性包括:1.語法簡潔易懂,適合初學者;2.動態類型系統,提高開發速度;3.豐富的標準庫,支持多種任務;4.強大的社區和生態系統,提供廣泛支持;5.解釋性,適合腳本和快速原型開發;6.多範式支持,適用於各種編程風格。

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

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

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器