在Python中删除空值的方法取决于您正在处理的数据类型。以下是几种常见情况下的空值删除方法:
删除Pandas DataFrame中的空值
import pandas as pd读取CSV文件df = pd.read_csv('data.csv')删除包含空值的行df = df.dropna()
删除列表中的空值
方法一:使用列表推导式
original_list = [1, 2, None, ' ', ' ', 4, '', 5]new_list = [x for x in original_list if x is not None and x != '']print(new_list)
方法二:使用`filter()`函数
original_list = [1, 2, None, ' ', ' ', 4, '', 5]new_list = list(filter(lambda x: x is not None and x != '', original_list))print(new_list)
处理字符串中的空格
去掉左边空格
string = ' * it is blank space test * 'print(string.lstrip())
去掉右边空格
string = ' * it is blank space test * 'print(string.rstrip())
去掉左右两边空格
string = ' * it is blank space test * 'print(string.strip())
去掉所有空格
string = ' * it is blank space test * 'str_new = string.replace(' ', '')print(str_new)
以上方法可以帮助您在Python中删除空值。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/32558.html