gpt4 book ai didi

python - 使用 pandas.read_csv 索引 DataFrame pandas

转载 作者:行者123 更新时间:2023-11-28 22:28:48 25 4
gpt4 key购买 nike

我有一个这种格式的文件文本:

            Value_1     Value_2     Value_3     Value_4     Value_5
10 MSX 0.40748157 0.223845099 0.14417411 0.434948943 0.804686917
20 MSX 0.679787708 0.669394102 0.09966376 0.295964602 0.741914305
30 MSX 0.746162656 0.325330912 0.739320885 0.999178387 0.492413352
40 MSX 0.320922967 0.015966342 0.599784939 0.621426555 0.393276648
50 MSX 0.306445206 0.412270302 0.18820778 0.605985775 0.21907484
60 MSX 0.238848223 0.188215196 0.546380095 0.683780446 0.868291677
70 MSX 0.181441931 0.868270404 0.483950835 0.398810737 0.874501167
80 MSX 0.559737008 0.991398039 0.737921625 0.998737594 0.033864231
90 MSX 0.648728689 0.832948225 0.558207809 0.712151967 0.11245818
100 MSX 0.467005098 0.378185352 0.347756793 0.098410037 0.189492058

我用 pandas.read_csv 读取这个文件是这样的:

import pandas

db = "data.txt"

a = pandas.read_csv(db, sep='\t')

例如,我想获取第 40 行和列 Value_3 的值。

当我使用时:

a["Value_3"]

我有 Value_3 的所有列值:

>>> a["Value_3"]
10 MSX 0.144174
20 MSX 0.099664
30 MSX 0.739321
40 MSX 0.599785
50 MSX 0.188208
60 MSX 0.546380
70 MSX 0.483951
80 MSX 0.737922
90 MSX 0.558208
100 MSX 0.347757
Name: Value_3

当我使用 ["40", "Value_3"] 时出现此错误消息:

Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
a["40","Value_3"]
File "C:\Program Files (x86)\python27\lib\site-packages\pandas\core\frame.py", line 1704, in __getitem__
return self._get_item_cache(key)
File "C:\Program Files (x86)\python27\lib\site-packages\pandas\core\generic.py", line 474, in _get_item_cache
values = self._data.get(item)
File "C:\Program Files (x86)\python27\lib\site-packages\pandas\core\internals.py", line 827, in get
_, block = self._find_block(item)
File "C:\Program Files (x86)\python27\lib\site-packages\pandas\core\internals.py", line 941, in _find_block
self._check_have(item)
File "C:\Program Files (x86)\python27\lib\site-packages\pandas\core\internals.py", line 948, in _check_have
raise KeyError('no item named %s' % str(item))
KeyError: "no item named ('40', 'Value_3')"

谁能帮帮我?

最佳答案

这里有很好的记录Advanced indexing with hierarchical index .

演示:

In [455]: df.loc[(slice(10,20), slice('MSX')), :]
Out[455]:
Value_1 Value_2 Value_3 Value_4 Value_5
10 MSX 0.407482 0.223845 0.144174 0.434949 0.804687
20 MSX 0.679788 0.669394 0.099664 0.295965 0.741914

关于python - 使用 pandas.read_csv 索引 DataFrame pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43373045/

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