在Python中删除空数据,你可以使用以下几种方法:
列表推导式:
```python
original_list = [1, 2, None, 3, '', 4, ' ', 5]
new_list = [x for x in original_list if x is not None and x != '']
print(new_list) 输出: [1, 2, 3, 4, 5]
filter()函数:
```python
original_list = [1, 2, None, 3, '', 4, ' ', 5]
new_list = list(filter(lambda x: x is not None and x != '', original_list))
print(new_list) 输出: [1, 2, 3, 4, 5]
remove()方法:
```python
cpuInfo = os.popen('adb shell top -d 1 -n 1 | findstr com.google.dialer').read()
cpuDetail = cpuInfo.split(' ')
cpuDetail.remove('')
print(cpuDetail) 输出: ['22542', 'u0_a118']
Pandas库:
```python
import pandas as pd
data = {'A': [1, 2, None, 4], 'B': [5, None, 7, 8], 'C': [None, 10, 11, 12]}
df = pd.DataFrame(data)
df.dropna(axis=1, how='all', inplace=True)
print(df) 输出: 删除空值所在列后的DataFrame
字符串操作:
```python
favorite_language = 'python python'
favorite_language = favorite_language.rstrip() 删除尾部空白
print(favorite_language) 输出: 'python'
文件操作:
```python
清空文件内容
with open('test.txt', 'w') as file:
file.truncate(0)
删除空目录
import os
def delete_empty_dir(dir):
if os.path.isdir(dir):
for d in os.listdir(dir):
path = os.path.join(dir, d)
if os.path.isdir(path) and not path.endswith('pic_neg'):
delete_empty_dir(path)
if not os.listdir(dir):
os.rmdir(dir)
print('删除完毕') 输出: 删除空目录后的消息
选择合适的方法根据你的具体需求,例如,如果你处理的是数据框(DataFrame),那么Pandas库可能是最方便的选择。如果你处理的是文件或列表,那么列表推导式或Pandas可能更适合。