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

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

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

问题

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

ATTGG
CATGC
GTGCC

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

我使用的命令是:

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

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

0 1 2 3 4 5
1 C A T G C
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:

ATTGG
CATGC
GTGCC

into several columns in a new dataframe.

The command I used is

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:

0 1 2 3 4 5
1 C A T G C
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

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

newdf = pd.DataFrame.from_records(df['col'].map(list))
print(newdf)

# 输出
   0  1  2  3  4
0  A  T  T  G  G
1  C  A  T  G  C
2  G  T  G  C  C
英文:

Convert your string to list before creating the dataframe:

newdf = pd.DataFrame.from_records(df['col'].map(list))
print(newdf)

# Output
   0  1  2  3  4
0  A  T  T  G  G
1  C  A  T  G  C
2  G  T  G  C  C


</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:

确定