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

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

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库来拆分数据框中的文本列。以下是翻译后的内容:

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

  1. import pandas as pd
  2. # 创建一个示例数据框
  3. df = pd.DataFrame({'col1': ['A,B,C', 'D,E', 'F']})
  4. # 使用str.split方法拆分'col1'列中的值
  5. df = df['col1'].str.split(',', expand=True).stack().reset_index(level=1, drop=True).rename('col1')
  6. # 结果数据框将对每个原始行产生多行
  7. print(df)

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

  1. 0 A
  2. 0 B
  3. 0 C
  4. 1 D
  5. 1 E
  6. 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 :

  1. import pandas as pd
  2. # Create a sample DataFrame
  3. df = pd.DataFrame({'col1': ['A,B,C', 'D,E', 'F']})
  4. # Use the str.split method to split the values in the 'col1' column
  5. df = df['col1'].str.split(',', expand=True).stack().reset_index(level=1, drop=True).rename('col1')
  6. # The resulting DataFrame will have multiple rows for each original row
  7. print(df)

This code will result something like this output:

  1. 0 A
  2. 0 B
  3. 0 C
  4. 1 D
  5. 1 E
  6. 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:

确定