Ero*_*mic 9 python numpy pandas
我正在使用代表图表的pandas DataFrame.数据帧由指示节点端点的MultiIndex索引.
建立:
import pandas as pd
import numpy as np
import itertools as it
edges = list(it.combinations([1, 2, 3, 4], 2))
# Define a dataframe to represent a graph
index = pd.MultiIndex.from_tuples(edges, names=['u', 'v'])
df = pd.DataFrame.from_dict({
'edge_id': list(range(len(edges))),
'edge_weight': np.random.RandomState(0).rand(len(edges)),
})
df.index = index
print(df)
## -- End pasted text --
edge_id edge_weight
u v
1 2 0 0.5488
3 1 0.7152
4 2 0.6028
2 3 3 0.5449
4 4 0.4237
3 4 5 0.6459
Run Code Online (Sandbox Code Playgroud)
我希望能够使用边缘子集索引图形,这就是我选择使用a的原因MultiIndex.只要输入df.loc是一个元组列表,我就能做到这一点.
# Select subset of graph using list-of-tuple indexing
edge_subset1 = [edges[x] for x in [0, 3, 2]]
df.loc[edge_subset1]
## -- End pasted text --
edge_id edge_weight
u v
1 2 0 0.5488
2 3 3 0.5449
1 4 2 0.6028
Run Code Online (Sandbox Code Playgroud)
但是,当我的边缘列表是一个numpy数组(通常是)或列表列表时,我似乎无法使用该df.loc属性.
# Why can't I do this if `edge_subset2` is a numpy array?
edge_subset2 = np.array(edge_subset1)
df.loc[edge_subset2]
## -- End pasted text --
TypeError: unhashable type: 'numpy.ndarray'
Run Code Online (Sandbox Code Playgroud)
如果我可以做到这一切就没问题arr.tolist(),但这会导致看似不同的错误.
# Why can't I do this if `edge_subset2` is a numpy array?
# or if `edge_subset3` is a list-of-lists?
edge_subset3 = edge_subset2.tolist()
df.loc[edge_subset3]
## -- End pasted text --
TypeError: '[1, 2]' is an invalid key
Run Code Online (Sandbox Code Playgroud)
list(map(tuple, arr.tolist()))每次我想选择一个子集时都必须使用它真的很痛苦.如果有另一种方法可以做到这一点会很好.
主要的任务是:
为什么我不能使用numpy数组.loc?是因为在引擎盖下使用字典将多索引标签映射到位置索引?
为什么列表列表会出现不同的错误?也许它真的是同样的问题,它只是采取了不同的方式?
是否有另一种(理想情况下更简洁)的方法来查找数据帧的子集,其中包含我不知道的多索引标签的数组?
字典键是不可变的,这基本上就是为什么你不能使用列表列表来访问多索引的原因。
为了能够访问多索引数据,loc您需要将numpy数组转换为元组列表;元组是不可变的,一种方法是使用map您提到的
如果您想避免使用地图并且正在读取 csv 文件中的边缘,则可以将它们读入数据框中,然后将to_records属性index设置为False,另一种方法可能是通过创建多索引,但ndarray您有在传递列表之前转置列表,以便每一层都是数组中的一个列表
import pandas as pd
df1 = df.loc[pd.MultiIndex.from_arrays(edge_subset2.T)]
print(df1)
#outputs
edge_id edge_weight
------ --------- -------------
(1, 2) 0 0.548814
(2, 3) 3 0.544883
(1, 4) 2 0.602763
Run Code Online (Sandbox Code Playgroud)
我发现pandas 文档中的 高级多重索引文章非常有帮助
| 归档时间: |
|
| 查看次数: |
676 次 |
| 最近记录: |