如何从数据框中删除\n并将数据移动到新行

2024-09-27 02:25:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框,看起来像这样

Index   column1   column2   column3
  0        3 \n9     2 \n89     8 \n56
  1        
  2        8         6          4
  3        4 \n9     12 \n12    32 \n5
  4                
  5         78       68           56

我想去掉\n,把剩下的内容移到下一个类似的地方。因此,我需要这样的数据帧

Index   column1   column2   column3
  0        3        2          8
  1        9        89         56 
  2        8        6          4
  3        4        12         32
  4        9        12         5
  5        78       68         56

我已经能够使用replace函数删除\n

df1.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""], regex=True)

但我无法将整数值9,89,56移动到下一行。可能吗

样本数据:

{'column1': {0: '3 \\n9', 1: '', 2: 8, 3: '4 \\n9', 4: '', 5: 78},
 'column2': {0: '2 \\n89', 1: '', 2: 6, 3: '12 \\n12', 4: '', 5: 68}, 
 'column3': {0: '8 \\n56', 1: '', 2: 4, 3: '32 \\n5', 4: '', 5: 56}}

Tags: 数据函数内容index地方replacedf1column1
3条回答

使用^{}^{}的单行程序

df1[['column1', 'column2', 'column3']] = \
    df1[['column1', 'column2', 'column3']].apply(
        lambda x: x.astype(str).str.extractall(r'([0-9]+)')\
             .reset_index(drop=True)[0])

一种方法是定义一个函数来展平列:

from itertools import chain

def flatten(col):
    return list(chain.from_iterable([i for i in col.str.split(r" \\n") if i]))

df[["column2","column3"]] = df[["column2","column3"]].apply(flatten)

print (df)

   Index  column1 column2 column3
0      0        3       2       8
1      1        7      89      56
2      2        8       6       4

编辑:使用新的示例数据,这里有一个更新的方法:

def flatten(col):
    return [i for i in chain.from_iterable(col.str.split(r" \n")) if i]

print (df.astype(str).apply(flatten))

  column1 column2 column3
0       3       2       8
1       9      89      56
2       8       6       4
3       4      12      32
4       9      12       5
5      78      68      56

使用:

def expand(col):
    return (
        col.astype(str)
        .replace('', np.nan).dropna().str.split(r"\s\\n")
        .explode().reset_index(drop=True)
    )


df[["column1", "column2", "column3"]] = df[[
    "column1", "column2", "column3"]].apply(expand)
print(df)

这张照片是:

  column1 column2 column3
0       3       2       8
1       9      89      56
2       8       6       4
3       4      12      32
4       9      12       5
5      78      68      56

相关问题 更多 >

    热门问题