首页 > 解决方案 > 如何在熊猫中剥离和分割

问题描述

有没有办法通过换行执行拆分,并在一行中执行一条空白?这就是我的 df 最初的样子

 df["Source"]
0       test1   \n test2   
1       test1   \n test2   
2       test1   \ntest2    
Name: Source, dtype: object

我曾经根据新行进行拆分并使用以下代码创建列表

Data = (df["Source"].str.split("\n").to_list())

Data
    [['test1   ', ' test2   '], ['   test1   ', ' test2   '], ['  test1   ', 'test2    ']]

我想进一步改进这一点并删除任何前导或尾随空格,我不确定如何在一行中使用拆分和剥离

df['Port']
0    443\n8080\n161
1                25
2               169
3                25
4          2014\n58
Name: Port, dtype: object

当我尝试根据新行拆分它时,它会为那些没有 \n 的值填充 nan 值

df['Port'].str.split("\n").to_list()
[['443', '8080', '161'], nan, nan, nan, ['2014', '58']]

同样适用于其他列

df['Source Hostname']
0    test1\ntest2\ntest3
1                  test5
2         test7\ntest8\n
3                  test1
4           test2\ntest4
Name: Source Hostname, dtype: object
df["Source Hostname"].str.split('\n').apply(lambda z: [e.strip() for e in z]).tolist()
[['test1', 'test2', 'test3'], ['test5'], ['test7', 'test8', ''], ['test1'], ['test2', 'test4']]

标签: pythonpandas

解决方案


df['Source'].str.split('\n').apply(lambda x: [e.strip() for e in x]).tolist()

推荐阅读