我有一个数组:
[(0, b'C', 5.8816, 6.0, 0.1184, 4.2631, 4.2631, 0.0)
(1, b'H', 0.8495, 1.0, 0.1505, 0.951, 0.951, 0.0)
(2, b'Br', 35.0064, 35.0, -0.0064, 1.2192, 1.2192, -0.0)
(3, b'Cl', 17.0401, 17.0, -0.0401, 1.2405, 1.2405, -0.0)
(4, b'F', 9.2225, 9.0, -0.2225, 1.0449, 1.0449, -0.0)]
我想从中提取单列浮点数,以便在程序中进一步使用。
当我尝试以下操作时:
QA = []
idx_IN_columns = [5]
QA = data[idx_IN_columns]
我明白了:
Traceback (most recent call last):
File "<ipython-input-22-4e6a1b6a3f36>", line 1, in <module>
runfile('C:/Users/Steve/Python/Testing/ReadFile_mpa_1.py', wdir='C:/Users/Steve/Python/Testing')
File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
enter code here
File "C:/Users/Steve/Python/Testing/ReadFile_mpa_1.py", line 34, in <module>
QA = data[idx_IN_columns]
IndexError: index 5 is out of bounds for axis 1 with size 5
非常感谢协助。
提前致谢
答案 0 :(得分:0)
data = [(0, b'C', 5.8816, 6.0, 0.1184, 4.2631, 4.2631, 0.0),
(1, b'H', 0.8495, 1.0, 0.1505, 0.951, 0.951, 0.0),
(2, b'Br', 35.0064, 35.0, -0.0064, 1.2192, 1.2192, -0.0),
(3, b'Cl', 17.0401, 17.0, -0.0401, 1.2405, 1.2405, -0.0),
(4, b'F', 9.2225, 9.0, -0.2225, 1.0449, 1.0449, -0.0)]
numbers = [n[2:] for n in data]
[(5.8816, 6.0, 0.1184, 4.2631, 4.2631, 0.0), (0.8495, 1.0, 0.1505, 0.951, 0.951, 0.0), (35.0064, 35.0, -0.0064, 1.2192, 1.2192, -0.0), (17.0401, 17.0, -0.0401, 1.2405, 1.2405, -0.0), (9.2225, 9.0, -0.2225, 1.0449, 1.0449, -0.0)]
答案 1 :(得分:0)
您的数据以及您尝试使用它的内容听起来非常适合Pandas,这是一个以表格格式处理数据的库。
>>> import pandas as pd
>>> data = [(0, b'C', 5.8816, 6.0, 0.1184, 4.2631, 4.2631, 0.0),
(1, b'H', 0.8495, 1.0, 0.1505, 0.951, 0.951, 0.0),
(2, b'Br', 35.0064, 35.0, -0.0064, 1.2192, 1.2192, -0.0),
(3, b'Cl', 17.0401, 17.0, -0.0401, 1.2405, 1.2405, -0.0),
(4, b'F', 9.2225, 9.0, -0.2225, 1.0449, 1.0449, -0.0)]
>>> df = pd.DataFrame(data)
>>> df
0 1 2 3 4 5 6 7
0 0 b'C' 5.8816 6.0 0.1184 4.2631 4.2631 0.0
1 1 b'H' 0.8495 1.0 0.1505 0.9510 0.9510 0.0
2 2 b'Br' 35.0064 35.0 -0.0064 1.2192 1.2192 -0.0
3 3 b'Cl' 17.0401 17.0 -0.0401 1.2405 1.2405 -0.0
4 4 b'F' 9.2225 9.0 -0.2225 1.0449 1.0449 -0.0
然后,要获得第5列,只需执行df[5]
。
>>> df[5]
0 4.2631
1 0.9510
2 1.2192
3 1.2405
4 1.0449
Name: 5, dtype: float64
通过使用Pandas,您还可以轻松地从(pd.read_csv()
)读取并将数据(df.to_csv()
)写入磁盘,例如。