如何将 Pandas DataFrame 中的列取消嵌套(分解)为多行
在 Pandas 中,分解列涉及将数据从单行转换为多行。当您有一列包含列表类型单元格并且需要将它们拆分为单独的行时,这非常有用。
考虑一个包含列表“B”列的 DataFrame:
df = pd.DataFrame({'A': [1, 2], 'B': [[1, 2], [1, 2]]}) Output: A B 0 1 [1, 2] 1 2 [1, 2]
到爆炸这列“B”,我们提出了各种方法:
方法 0 [Pandas >= 0.25]
从 Pandas 0.25 开始,如果只需要爆炸一列,请使用 pandas.DataFrame.explode 函数:
df.explode('B') Output: A B 0 1 1 1 1 2 3 2 1 4 2 2
方法 1
应用pd.Series(容易理解,但不推荐性能):
df.set_index('A').B.apply(pd.Series).stack().reset_index(level=0).rename(columns={0:'B'})
方法 2
在 DataFrame 构造函数中使用重复:
df = pd.DataFrame({'A': df.A.repeat(df.B.str.len()), 'B': np.concatenate(df.B.values)})
方法 3
Re -创建list:
pd.DataFrame([[x] + [z] for x, y in df.values for z in y], columns=df.columns)
方法 4
使用 reindex 或 loc:
df.reindex(df.index.repeat(df.B.str.len())).assign(B=np.concatenate(df.B.values))
方法 5
当列表仅包含唯一的值:
from collections import ChainMap d = dict(ChainMap(*map(dict.fromkeys, df['B'], df['A']))) pd.DataFrame(list(d.items()), columns=df.columns[::-1])
方法 6
使用 NumPy 实现高性能:
newvalues = np.dstack((np.repeat(df.A.values, list(map(len, df.B.values))), np.concatenate(df.B.values))) pd.DataFrame(data=newvalues[0], columns=df.columns)
方法 7
使用 itertools循环和chain:
from itertools import cycle, chain l = df.values.tolist() l1 = [list(zip([x[0]], cycle(x[1])) if len([x[0]]) > len(x[1]) else list(zip(cycle([x[0]]), x[1]))) for x in l] pd.DataFrame(list(chain.from_iterable(l1)), columns=df.columns)
泛化为多列
要处理多个爆炸列,可以定义一个函数:
def unnesting(df, explode): idx = df.index.repeat(df[explode[0]].str.len()) df1 = pd.concat([ pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1) df1.index = idx return df1.join(df.drop(explode, 1), how='left') unnesting(df, ['B', 'C'])
Column-明智的取消嵌套
要水平扩展列表,请使用 pd.DataFrame构造函数:
df.join(pd.DataFrame(df.B.tolist(), index=df.index).add_prefix('B_'))
以上是如何将 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
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver Mac版
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

WebStorm Mac版
好用的JavaScript开发工具

Atom编辑器mac版下载
最流行的的开源编辑器

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中