在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中删除空值。