将 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,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

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


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

禅工作室 13.0.1
功能强大的PHP集成开发环境

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器