gpt4 book ai didi

python - 在 Pandas 中使用 DataFrame.ix 和元组索引

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:54 24 4
gpt4 key购买 nike

我有一堆使用元组作为索引的 Pandas 代码。我最近遇到需要使用 DataFrame.ix 访问 DataFrame 的单个元素,这被元组弄糊涂了。它似乎认为我的元组是我想要访问的一系列键,而不是我想要访问的单个键(恰好是一个序列)。如何提取以元组为键的单个行?

也许这是一个警示故事,不要在 Pandas 索引中使用序列,但就我而言,为时已晚。

import string, pandas as pd, numpy as np

bar = pd.DataFrame(np.random.random((8,2)))
bar.columns = ['col1', 'col2']
bar.index = list(string.ascii_lowercase)[:8]
print bar
print bar.iloc[0].name
print bar.ix[bar.iloc[0].name]

bar.index = [tuple(list(string.ascii_lowercase)[i:i+3]) for i in range(8)]
print bar.iloc[0].name
print bar.ix[bar.iloc[0].name] # Fails with `KeyError: 'a'`

最佳答案

您可以将元组包装在列表中以使其工作。

In [17]: bar.ix[[bar.iloc[0].name]]
Out[17]:
col1 col2
(a, b, c) 0.216689 0.262511

关于python - 在 Pandas 中使用 DataFrame.ix 和元组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25476880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com