Skip to main content
 首页 » 编程设计

python之处理缺失数据

2025年05月04日11tuyile006

我有以下数据框:

from pandas import * 
from math import * 
data=read_csv('agosto.csv') 
 
 
      Fecha         DirViento MagViento 
0 2011/07/01 00:00      N       6.6 
1 2011/07/01 00:15      N       5.5 
2 2011/07/01 00:30      N       6.6 
3 2011/07/01 00:45      N       7.5 
4 2011/07/01 01:00     ---      6.0 
5 2011/07/01 01:15     ---      7.1 
6 2011/07/01 01:30      S      4.7 
7 2011/07/01 01:45      SE      3.1  
.  
. 
. 

我要做的第一件事,是将风值转换为数值,以获得u和v风分量。但是当我执行操作时,丢失的数据(---)会产生冲突。

direccion=[] 
for i in data['DirViento']: 
    if i=='SSW': 
     dir=202.5 
    if i=='S': 
     dir=180.0 
    if i=='N': 
     dir=360.0 
    if i=='NNE': 
     dir=22.5 
    if i=='NE': 
     dir=45.0 
    if i=='ENE': 
     dir=67.5 
    if i=='E': 
     dir=90.0 
    if i=='ESE': 
     dir=112.5 
    if i=='SE': 
     dir=135.0 
    if i=='SSE': 
     dir=157.5 
    if i=='SW': 
     dir=225.0 
    if i=='WSW': 
     dir=247.5 
    if i=='W': 
     dir=270.0 
    if i=='WNW': 
     dir=292.5 
    if i=='NW': 
     dir=315.0 
    if i=='NNW': 
     dir=337.5 
    direccion.append(dir) 
data['DirViento']=direccion 

我得到以下信息:

data['DirViento'].head() 
0    67.5 
1    67.5 
2    67.5 
3    67.5 
4    67.5 

因为缺失的数据被赋予了其他行的值? get的组件,代码如下

Vviento=[] 
Uviento=[] 
for i in range(0,len(data['MagViento'])): 
    Uviento.append((data['MagViento'][i]*sin((data['DirViento'][i]+180)*(pi/180.0)))) 
    Vviento.append((data['MagViento'][i]*cos((data['DirViento'][i]+180)*(pi/180.0)))) 
 
data['PromeU']=Uviento 
data['PromeV']=Vviento 

现在分组获取统计数据

index=data.set_index(['Fecha','Hora'],inplace=True) 
g = index.groupby(level=0) 

但是我得到了错误

IndexError: index out of range for array 

我做错了什么吗?如何在不考虑缺失数据的情况下进行运算?

请您参考如下方法:

我在您的代码中看到一个流程。你的条件语句应该更像:

if i == 'SSW': 
    dir = 202.5 
elif i == 'S': 
... 
else: 
    dir = np.nan  

或者您可以在循环开始时清除 dir 变量。否则,缺少数据的行的 dir 将与上一次迭代的 dir 相同。
但我认为这段代码可以用更 pythonic 的方式改进,例如,像这样。

# test DataFrame 
df = pd.DataFrame({'DirViento':['N', 'N', 'N', 'N', '--', '--', 'S', 'SE']) 
 
  DirViento 
0         N 
1         N 
2         N 
3         N 
4        -- 
5        -- 
6         S 
7        SE   
 
# create points of compass list 
dir_lst = ['NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','WSW','W','WNW','NW','NNW','N'] 
# create dictionary from it 
dir_dict = {x: (i + 1) *22.5 for i, x in enumerate(dir_lst)} 
# add a new column 
df['DirViento2'] = df['DirViento'].apply(lambda x: dir_dict.get(x, None)) 
 
  DirViento  DirViento2 
0         N         360 
1         N         360 
2         N         360 
3         N         360 
4        --         NaN 
5        --         NaN 
6         S         180 
7        SE         135 

更新 @DanAllan 在评论中提出的好建议,代码变得更短,更像 pythonic:

df['DirViento2'] = df['DirViento'].replace(dir_dict)