我正在通过ThinkStats学习,但我也决定一路学习熊猫。因此下面的代码从文件中读入数据,进行一些检查,然后将数据附加到列表中。最后我列出了几个包含我需要的数据的列表。下面的代码是有效的(除了扰乱列…)
我的问题是:从这些列表构建数据帧的最佳方法是什么?更一般地说,我是否以最有效的方式实现了我的目标?你知道吗
preglength = []
caseid = []
outcome = []
birthorder = []
finalweight = []
with open('2002FemPreg.dat') as f:
for line in f:
caseid.append(int(line[0:13].strip()))
preglength.append(int(line[274:276].strip()))
outcome.append(int(line[276].strip()))
try:
birthorder.append(int(line[277:279]))
except ValueError:
birthorder.append(np.nan)
finalweight.append(float(line[422:440].strip()))
c1 = pd.Series(caseid)
c2 = pd.Series(preglength)
c3 = pd.Series(outcome)
c4 = pd.Series(birthorder)
c5 = pd.Series(finalweight)
data = pd.DataFrame({'caseid': c1,'preglength': c2,'outcome': c3,'birthorder': c4,'weight': c5})
print(data.head())
我可能会使用^{} :
相关问题 更多 >
编程相关推荐