使用`.str.split(expand=True)`为什么会丢失信息?

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

Why am I losing information with .str.split(expand=True)?

问题

我正在尝试扩展一个由字符串组成的数据框的列,类似于这样:

  1. ATTGG
  2. CATGC
  3. GTGCC

将其转换为一个新数据框中的多列。

我使用的命令是:

  1. newdf = pd.DataFrame(df['col'].str.split("", expand=True))

在打印时,我发现第一列和第一行实际上是索引:

  1. 0 1 2 3 4 5
  2. 1 C A T G C
  3. 2 G T G C C

而且我的第一行被截断了,可能是因为索引的存在。

为什么我的第一行被截断了?我可以怎么做来修复这个问题?

英文:

I'm trying to expand a column of a dataframe which is made up of strings, something like this:

  1. ATTGG
  2. CATGC
  3. GTGCC

into several columns in a new dataframe.

The command I used is

  1. newdf = pd.DataFrame(df['col'].str.split("", expand = True)

When printing, I found that the first column and the first row are actually the index:

  1. 0 1 2 3 4 5
  2. 1 C A T G C
  3. 2 G T G C C

and that my first row is cut off, presumably because of the presence of the index.

Why is my first row cut off? What can I do to fix this?

答案1

得分: 1

将字符串转换为列表后再创建数据框:

  1. newdf = pd.DataFrame.from_records(df['col'].map(list))
  2. print(newdf)
  3. # 输出
  4. 0 1 2 3 4
  5. 0 A T T G G
  6. 1 C A T G C
  7. 2 G T G C C
英文:

Convert your string to list before creating the dataframe:

  1. newdf = pd.DataFrame.from_records(df['col'].map(list))
  2. print(newdf)
  3. # Output
  4. 0 1 2 3 4
  5. 0 A T T G G
  6. 1 C A T G C
  7. 2 G T G C C
  8. </details>

huangapple
  • 本文由 发表于 2023年1月9日 03:21:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050639.html
匿名

发表评论

匿名网友

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

确定