是否有一种方法可以通过换行来执行拆分,并且还可以在一行中添加空白? 这就是我的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']]
答案 0 :(得分:1)
使用Series.str.strip
删除对白的空白,然后使用split
通过正则表达式\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']]
答案 1 :(得分:1)
df['Source'].str.split('\n').apply(lambda x: [e.strip() for e in x]).tolist()