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
当我尝试根据新行拆分它时,它会为那些没有 \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']]
解决方案
df['Source'].str.split('\n').apply(lambda x: [e.strip() for e in x]).tolist()
推荐阅读
- javascript - 单击时更改图标
- c++ - C ++允许self类型的成员容器但不允许成员对象?
- python - 将 python 数组打印保存到 .csv
- r - 根据分组列名将函数和计算应用于一组列
- r - 无法将 sliderInput 与 selectInput 链接以操纵圆环图
- react-native - 使用异步函数获取 NetInfo
- c++ - 在 Raspberry Pi 上但不在 Linux 上运行代码时出现 Eigen 库矩阵对齐错误
- python-3.x - UserString 子类的未解析属性“数据”
- sql-server - SQL Server CPU 永久卡在 100%
- jquery - 在使用 TableTools 扩展提交 DataTable 按钮之前要求用户输入