我在填充 pandas DataFrame
时遇到一些问题。我按照指示找到here生成一个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)
Exception: Data must be 1-dimensional
如果我用 randn(1)
替换 randn(1, 5)
,它就可以正常工作。对于 randn(1, 1)
我应该使用 randn(1, 1).flatten('F')
但也可以。
尝试时:
v = pd.Series(np.random.randn(1, 5).flatten('F'), index=index)
ValueError: Wrong number of items passed 5, placement implies 1
我的目的是为每个 添加 1 个特征向量(当然在实际场景中它们是
和 np.array
而不是 np.random.randn
)每行中的 Activityid
。
那么,如何在 MultiIndex
DataFrame
中添加数组?
编辑:
由于我是 pandas 新手,因此我将 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
最佳答案
存在问题 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: float64
关于python - 将 numpy 数组附加到多索引数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50325541/