【发布时间】:2017-12-31 14:53:45
【问题描述】:
我知道通常 pandas 的 itertuples() 会返回每个值,包括列名,如下所示:
ab=pd.DataFrame(np.random.random([3,3]),columns=['hi','low','med'])
for i in ab.itertuples():
print(i)
输出如下:
Pandas(Index=0, hi=0.05421443, low=0.2456833, med=0.491185)
Pandas(Index=1, hi=0.28670429, low=0.5828551, med=0.279305)
Pandas(Index=2, hi=0.53869406, low=0.3427290, med=0.750075)
但是,我不知道为什么它没有按照我对另一组代码的预期显示列,如下所示:
us qqq equity us spy equity
date
2017-06-19 0.0 1.0
2017-06-20 0.0 -1.0
2017-06-21 0.0 0.0
2017-06-22 0.0 0.0
2017-06-23 1.0 0.0
2017-06-26 0.0 0.0
2017-06-27 -1.0 0.0
2017-06-28 1.0 0.0
2017-06-29 -1.0 0.0
2017-06-30 0.0 0.0
上面是一个 Pandas Dataframe,以 Timestamp 为索引,float64 为列表中的值,以字符串 ['us qqqEquity','us spyEquity'] 为列的列表。
当我这样做时:
for row in data.itertuples():
print (row)
将列显示为 _1 和 _2,如下所示:
Pandas(Index=Timestamp('2017-06-19 00:00:00'), _1=0.0, _2=1.0)
Pandas(Index=Timestamp('2017-06-20 00:00:00'), _1=0.0, _2=-1.0)
Pandas(Index=Timestamp('2017-06-21 00:00:00'), _1=0.0, _2=0.0)
Pandas(Index=Timestamp('2017-06-22 00:00:00'), _1=0.0, _2=0.0)
Pandas(Index=Timestamp('2017-06-23 00:00:00'), _1=1.0, _2=0.0)
Pandas(Index=Timestamp('2017-06-26 00:00:00'), _1=0.0, _2=0.0)
Pandas(Index=Timestamp('2017-06-27 00:00:00'), _1=-1.0, _2=0.0)
Pandas(Index=Timestamp('2017-06-28 00:00:00'), _1=1.0, _2=0.0)
Pandas(Index=Timestamp('2017-06-29 00:00:00'), _1=-1.0, _2=0.0)
Pandas(Index=Timestamp('2017-06-30 00:00:00'), _1=0.0, _2=0.0)
有人知道我做错了什么吗?创建原始数据框时是否与某些变量引用问题有关? (另外,作为一个附带问题,我从社区了解到,从 itertuples() 生成的数据类型应该是元组,但似乎(如上所示),返回类型是我从 type 语句中验证的?)
感谢大家的耐心等待,我还在努力掌握 DataFrame 的应用。
【问题讨论】:
-
data.columns说什么? -
@Willem Van Onsem 上面写着
Index(['us qqq equity', 'us spy equity'], dtype='object')
标签: python pandas dataframe iteration