处理缺失的d

2024-10-04 05:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

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

我做错什么了吗?如何在不考虑缺失数据的情况下执行操作?你知道吗


Tags: csv数据fromimportfordataindexif
1条回答
网友
1楼 · 发布于 2024-10-04 05:26:41

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

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

或者可以清除循环开头的dir变量。否则,缺少数据的行的dir将与上一次迭代的dir相同。
但我认为这段代码可以用更具python风格的方式来改进,例如,类似这样的东西。你知道吗

# 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的好建议在评论中,代码变得更短,甚至更像python:

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

相关问题 更多 >