如何在Pandas身上脱衣和分裂

2024-04-25 17:43:44 发布

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

有没有一种方法可以执行按新行拆分,也可以在一行中执行一条空白? 这就是我的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

当我尝试基于新行拆分它时,它会为没有的填充nan值\n

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']]

Tags: tonamesourcedfdataobjectportnan
2条回答
df['Source'].str.split('\n').apply(lambda x: [e.strip() for e in x]).tolist()

使用^{}删除跟踪空格,然后使用regex \s*\n\s*删除\n前后的一个或零个空格:

df = pd.DataFrame({'Source':['test1   \n test2   ',
                             '    test1   \n test2   ',
                             '    test1   \ntest2   ']})
print (df)
                    Source
0      test1   \n test2   
1      test1   \n test2   
2       test1   \ntest2

Data = (df["Source"].str.strip().str.split("\s*\n\s*").to_list())
print (Data)
[['test1', 'test2'], ['test1', 'test2'], ['test1', 'test2']]

或者,如果可能的话,可以用任意空格分割(这里指空格或\n):

Data = (df["Source"].str.strip().str.split().to_list())
print (Data)
[['test1', 'test2'], ['test1', 'test2'], ['test1', 'test2']]

相关问题 更多 >