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

标签 python pandas

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

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

我已经能够使用替换功能删除\n

df1.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""],正则表达式=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}}

最佳答案

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

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

关于python - 如何从数据框中删除\n并将数据移动到新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61452219/

相关文章:

python - 图像中的不可见水印

python - 如何将一系列 str 列表与一系列 str 连接起来

python - 如何使用 matplotlib 从 csv 绘制特定日期和时间的数据?

python - 如何使用 pandas 间隔来查找值,以填充另一个数据框

python - 根据条件在 Pandas、Python 中编辑计划文件的顺序和内容

python-3.x - 获取每个 id 的所有列,其中该列等于某个值

python - 图像校正 - OpenCV - Python

python - 动态修改 Python 方法和参数

python - 在 Windows 后台根据键盘记录器输入运行 Python Clicker

python - numpy 中的一些奇怪的东西