将Pandas数据框中的单元格拆分为多行的Python代码。

huangapple go评论48阅读模式
英文:

Python code to split cell into multiple rows in pandas dataframe

问题

如何在pandas数据框中将单元格拆分为多行

英文:

How can I split cell into multiple rows in pandas dataframe

将Pandas数据框中的单元格拆分为多行的Python代码。

将Pandas数据框中的单元格拆分为多行的Python代码。

答案1

得分: 0

代码中的内容是关于如何使用Python中的Pandas库来拆分数据框中的文本列。以下是翻译后的内容:

问题并不十分清晰,不清楚你想拆分哪些单元格/单元格类型,但无论如何,做法如下:

import pandas as pd

# 创建一个示例数据框
df = pd.DataFrame({'col1': ['A,B,C', 'D,E', 'F']})

# 使用str.split方法拆分'col1'列中的值
df = df['col1'].str.split(',', expand=True).stack().reset_index(level=1, drop=True).rename('col1')

# 结果数据框将对每个原始行产生多行
print(df)

这段代码的输出将类似于以下内容:

0    A
0    B
0    C
1    D
1    E
2    F

尝试从这个示例中获取灵感!

英文:

The question is not very clear what cells / kind of cells you want to split, but anyway the way to do so is :

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'col1': ['A,B,C', 'D,E', 'F']})

# Use the str.split method to split the values in the 'col1' column
df = df['col1'].str.split(',', expand=True).stack().reset_index(level=1, drop=True).rename('col1')

# The resulting DataFrame will have multiple rows for each original row
print(df)

This code will result something like this output:

0    A
0    B
0    C
1    D
1    E
2    F

Try to get inspiration from this snippet !

huangapple
  • 本文由 发表于 2023年2月8日 22:53:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定