如何将 Pandas DataFrame 中的逗号分隔字符串拆分为单独的行?
拆分 Pandas DataFrame 中的逗号分隔字符串条目以创建单独的行
问题:
我们有一个 Pandas DataFrame,其中一列中包含带有逗号分隔值的字符串。我们希望拆分每个 CSV 条目并为每个唯一值创建一个新行。例如,“a,b,c”应变为“a”,“b”,“c”。
解决方案:
选项 1: DataFrame.explode() (Pandas 0.25.0 )
DataFrame.explode() 方法是专门为此目的而设计的。它允许我们将类似列表的列(在本例中为逗号分隔的字符串)拆分为单独的行。
In [1]: df.explode('var1') Out[1]: var1 var2 var3 0 a 1 XX 1 b 1 XX 2 c 1 XX 3 d 2 ZZ 4 e 2 ZZ 5 f 2 ZZ 6 x 2 ZZ 7 y 2 ZZ
选项 2:自定义向量化函数
如果 DataFrame.explode() 不可用或者我们需要更多定制,我们可以创建自己的矢量化函数:
import numpy as np def explode(df, lst_cols, fill_value='', preserve_index=False): # Convert `lst_cols` to a list if it is a string. if isinstance(lst_cols, str): lst_cols = [lst_cols] # Calculate the lengths of each list in `lst_cols`. lens = df[lst_cols[0]].str.len() # Create a new index based on the lengths of the lists. idx = np.repeat(df.index.values, lens) # Create a new DataFrame with the exploded columns. exp_df = 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 necessary. if (lens == 0).any(): exp_df = exp_df.append(df.loc[lens == 0, df.columns.difference(lst_cols)], sort=False).fillna(fill_value) # Revert the original index order and reset the index if requested. exp_df = exp_df.sort_index() if not preserve_index: exp_df = exp_df.reset_index(drop=True) return exp_df
用法示例:
In [2]: explode(df, 'var1') Out[2]: var1 var2 var3 0 a 1 XX 1 b 1 XX 2 c 1 XX 3 d 2 ZZ 4 e 2 ZZ 5 f 2 ZZ 6 x 2 ZZ 7 y 2 ZZ
以上是如何将 Pandas DataFrame 中的逗号分隔字符串拆分为单独的行?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

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

Dreamweaver CS6
视觉化网页开发工具

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

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...
