我在养熊猫DataFrame上遇到了一些困难。我正在按照“找到这里”的指令来生成一个MultiIndex DataFrame。这个例子很好,只是我想要一个数组,而不是一个值。
activity = 'Open_Truck'
id = 1
index = pd.MultiIndex.from_tuples([(activity, id)], names=['activity', 'id'])
v = pd.Series(np.random.randn(1, 5), index=index)例外:数据必须是一维的。
如果我将randn(1, 5)替换为randn(1),它就能正常工作。对于randn(1, 1),我应该使用randn(1, 1).flatten('F'),但也可以。在尝试时:
v = pd.Series(np.random.randn(1, 5).flatten('F'), index=index)ValueError:错误的项目数通过5,放置意味着1
我的目的是为每一行的每个np.array和id添加一个特征向量(当然在实际场景中是np.random.randn,而不是np.random.randn)。
那么,如何在MultiIndex DataFrame中添加数组呢?
编辑:
因为我刚开始接触熊猫,所以我把Series和DataFrame混在一起。我可以使用默认是二维的DataFrame来实现上面的内容:
arrays = [np.array(['Open_Truck']*2),
np.array(['1', '2'])]
df = pd.DataFrame(np.random.randn(2, 4), index=arrays)
df
0 1 2 3
Open 1 -0.210923 0.184874 -0.060210 0.301924
2 0.773249 0.175522 -0.408625 -0.331581发布于 2018-05-14 08:00:54
存在问题,MultiIndex只有一个元组,而且数据长度不同,5因此长度不匹配:
activity = 'Open_Truck'
id = 1
#get 5 times tuples
index = pd.MultiIndex.from_tuples([(activity, id)] * 5, names=['activity', 'id'])
print (index)
MultiIndex(levels=[['Open_Truck'], [1]],
labels=[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
names=['activity', 'id'])
print (len(index))
5
v = pd.Series(np.random.randn(1, 5).flatten('F'), index=index)
print (v)
activity id
Open_Truck 1 -1.348832
1 -0.706780
1 0.242352
1 0.224271
1 1.112608
dtype: float64在第一个过程中,长度是相同的,1,因为列表中有一个元组:
activity = 'Open_Truck'
id = 1
index = pd.MultiIndex.from_tuples([(activity, id)], names=['activity', 'id'])
print (len(index))
1
v = pd.Series(np.random.randn(1), index=index)
print (v)
activity id
Open_Truck 1 -1.275131
dtype: float64https://stackoverflow.com/questions/50325541
复制相似问题