有没有一种方法可以执行按新行拆分,也可以在一行中执行一条空白? 这就是我的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']]
使用^{} 删除跟踪空格,然后使用regex
\s*\n\s*
删除\n
前后的一个或零个空格:或者,如果可能的话,可以用任意空格分割(这里指空格或
\n
):相关问题 更多 >
编程相关推荐