带分离器的分离柱

YIPYIP:
| A             | B
| a;b;c         | 1;2;3
| a;b;c;d       | 1

为了拆分列,我正在使用

new = df["A"].str.split(";", n=5, expand=True).
df['A1'] = new[0]
df['A2'] = new[1]
df['A3'] = new[2]
df['A4'] = new[3]
df.drop(columns=["A"], inplace=True)

df['B1'] = new[0]
df['B2'] = new[1]
df['B3'] = new[2]
df.drop(columns=["B"], inplace=True)

还有其他替代方法,使我不需要计算每列中的数据数量吗?我仍然需要输出是这样的:

| A1| A2| A3| A4| B1| B2| B3
| a | b | c |   | 1 | 2 | 3
| a | b | c | d | 1 |   | 

谢谢!

ALollz:

无需指定拆分数量,因为默认情况下,它将在分隔符的每个实例上拆分。结果将是一个DataFrame,其中列为RangeIndex,因此将列添加为前缀。循环遍历每个Series(因为它是Series.str.split),然后concat加入结果。

df = pd.concat([df[col].str.split(';', expand=True).add_prefix(col) for col in df.columns],
               axis=1)

  A0 A1 A2    A3 B0    B1    B2
0  a  b  c  None  1     2     3
1  a  b  c     d  1  None  None

请注意,这些'B'列包含字符串,'1'因此,如果要使用数字pd.to_numeric

numerics = df.columns[df.columns.str.startswith('B')]
df[numerics] = df[numerics].apply(pd.to_numeric, errors='coerce')

  A0 A1 A2    A3  B0   B1   B2
0  a  b  c  None   1  2.0  3.0
1  a  b  c     d   1  NaN  NaN

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章