【发布时间】:2021-08-31 08:32:35
【问题描述】:
我刚开始使用 python。 下面的代码有效,但我认为它不符合编码标准:
- 我在函数
determine_direction中遇到错误 - 我看到的每一个地方,聪明人都说你应该避免错误并改用 apply 函数。
有人可以帮我吗?
import pandas as pd
def determine_direction(df, fl_wr):
# look up wind direction based on degrees
# input: degrees - float
# output: wind direction - string
df_vlaremwindsel = df[(df['from'] <= fl_wr)]
df_vlaremwindsel = df_vlaremwindsel[(fl_wr < df['to'])]
str_direction = df_vlaremwindsel.index[0]
return str_direction
# dataframe 1
lst_1 = {'NO': [22.5, 67.5], 'O': [67.5, 112.5], 'ZO': [112.5, 157.5], 'Z': [157.5, 202.5],
'ZW': [202.5, 257.5], 'W': [257.5, 292.5], 'NW': [292.5, 337.5], 'NNW': [337.5, 360.5],
'NNO': [0.5, 22.5], 'N': [0, 0.5]}
df_1= pd.DataFrame.from_dict(data=lst_1, orient='index', columns=['from', 'to'])
# dataframe 2 - testdata with degrees
lst_2 = [25.0, 88.1, 11, 356, 278, 169, 69, 1, 246]
df_2= pd.DataFrame.from_dict(data=lst_2)
# add empty column
df_2['direction']=''
#works, but i want to use .apply function
for i in range(len(df_2)):
df_2.loc[i,['direction']] = determine_direction(df_1, df_2.iloc[i, 0])
print(df_2)
# apply function: does not work
# df_2['direction'].apply(determine_direction(df_1, df_2.loc['0']))
【问题讨论】: