Python 使用numpy(作为重新索引)提取数据帧特征
我有一个numpy数组,如下所示:Python 使用numpy(作为重新索引)提取数据帧特征,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,我有一个numpy数组,如下所示: [[1,521,3], [2,543,2], [3,555,3], [4,575,2]] 在熊猫中,它看起来像这样: Seconds Price Type 1 521 3 2 543 2 3 555 3 4 575 2 然后我为它设置索引: types = df.T.unique() df.set_index(['Type'
[[1,521,3],
[2,543,2],
[3,555,3],
[4,575,2]]
在熊猫中,它看起来像这样:
Seconds Price Type
1 521 3
2 543 2
3 555 3
4 575 2
然后我为它设置索引:
types = df.T.unique()
df.set_index(['Type','Seconds'], inplace=True)
输出:
Price
Type Seconds
3 1 521
3 3 555
2 2 543
2 4 575
Price
Type Seconds
3 1 521
3 2 0
3 3 555
3 4 0
2 1 0
2 2 543
2 3 0
2 4 575
然后,我重新编制了索引,为每种类型设置了每秒钟的索引:
for i in types:
df1 = df.xs(i, level=0).reindex([1,2,3,4], fill_value=0).reset_index()
df['Type'] = i
df.set_index(['Type', 'Seconds'], inplace=True)
输出:
Price
Type Seconds
3 1 521
3 3 555
2 2 543
2 4 575
Price
Type Seconds
3 1 521
3 2 0
3 3 555
3 4 0
2 1 0
2 2 543
2 3 0
2 4 575
在熊猫身上做这件事很容易。在numpy怎么做?
它应该是这样的:
df.values
这里有一个方法你可以使用
import numpy as np
ar = np.array([[1,521,3], [2,543,2], [3,555,3], [4,575,2]])
ar
Out[50]:
array([[ 1, 521, 3],
[ 2, 543, 2],
[ 3, 555, 3],
[ 4, 575, 2]])
确定您的扩展索引:
u0 = np.unique(ar[:, 0])
u2 = np.unique(ar[:, 2])
rowcount = u0.shape[0]*u2.shape[0]
rows = np.stack([np.repeat(u2, rowcount//u2.shape[0]),
np.tile(u0, rowcount//u0.shape[0])],
1)
rows
Out[51]:
array([[2, 1],
[2, 2],
[2, 3],
[2, 4],
[3, 1],
[3, 2],
[3, 3],
[3, 4]])
找出阵列中尚未包含的内容:
row_index = np.sort(np.unique(np.concatenate([ar[:, [2, 0]], rows]),
return_index=True, axis=0)[1])
missing = rows[row_index[ar.shape[0]:]-ar.shape[0]]
missing
Out[52]:
array([[2, 1],
[2, 3],
[3, 2],
[3, 4]])
然后合并:
reindexed = np.zeros((rowcount, ar.shape[1]), int)
reindexed[:ar.shape[0], [1, 2, 0]] = ar
reindexed[ar.shape[0]:, [0, 1]] = missing
reindexed
Out[53]:
array([[ 3, 1, 521],
[ 2, 2, 543],
[ 3, 3, 555],
[ 2, 4, 575],
[ 2, 1, 0],
[ 2, 3, 0],
[ 3, 2, 0],
[ 3, 4, 0]])
如果需要,进行排序:
reindexed[np.lexsort([reindexed[:, 1], reindexed[:, 0]])]
Out[49]:
array([[ 2, 1, 0],
[ 2, 2, 543],
[ 2, 3, 0],
[ 2, 4, 575],
[ 3, 1, 521],
[ 3, 2, 0],
[ 3, 3, 555],
[ 3, 4, 0]])
我认为您的行
df.reindex([1,2,3,4],fill\u value=0)
不会产生错误。你用的是什么版本的熊猫?@TEDPROU为这个错误感到抱歉。我已经编辑过了,你能再检查一下吗?第四行代码错误,第三行。形状不匹配:形状(0,2)的值数组无法广播到形状(2,4)的索引结果@NurislomRakhmatullaev,这就是原因。您需要np.unique
中的axis参数,不能跳过它。如果它不接受axis参数,则您的numpy版本已过时。轴参数添加在1.13中。