我是Python新手,我正在练习数据框架。
我有一个data
框架,其中一列包含字符串格式("OCTOBER","NOVEMBER" etc)
的月份。
我写了一个简单的for
循环,以便获得一个带有数值的新列。
for x in range(0,39053):
if data.iloc[x,25]=="DEC":
data["month"]=12
elif data.iloc[x,25]=="OCT":
data["month"]=10
elif data.iloc[x,25]=="JUL":
data["month"]=7
elif data.iloc[x,25]=="SEP":
data["month"]=9
elif data.iloc[x,25]=="AUG":
data["month"]=8
elif data.iloc[x,25]=="JUN":
data["month"]=8
elif data.iloc[x,25]=="MAY":
data["month"]=5
elif data.iloc[x,25]=="APR":
data["month"]=4
elif data.iloc[x,25]=="MAR":
data["month"]=3
elif data.iloc[x,25]=="FEB":
data["month"]=2
elif data.iloc[x,25]=="JAN":
data["month"]=1
elif data.iloc[x,25]=="NOV":
data["month"]=11
出于某种原因,即使我知道所有月份都有条目,我仍然会将所有值都等于11
。
例如,如果我运行以下代码,则返回值True
的{{1}}
"DEC"
我理解我编写的代码的方式是,对于每一行,您在第25列(即月份)中获取变量的值,然后在第一次满足条件时获取对应的数值
满足条件后,您将停止查看并移至下一行。
我知道我在哪里弄错了吗?
答案 0 :(得分:0)
回答这个问题,我们必须了解data.iloc的数据类型是什么,以及如何访问data.iloc [45,25]? - 如果iloc是以元组(45,25)为键的字典,则访问data.iloc [(x,25)]。