python - 使用 Python 从包含多组数据的文件中读取指定列
问题描述
我正在尝试使用 python 从 .txt 文件中加载多列数据。
我的文件包含多组数据,每组都有一个标题。
我想选择一组,然后从中选择 2 列。我正在使用 genfromtxt 读取 .txt 文件,但它将集合的标题读取为列,因此它给了我这种错误:
第 2 行(得到 4 列而不是 1 列)
这是我的 txt 文件的示例,其中 TC_14TeV_NLO 和 TC_13TeV_LO 是标题,我想取每组的前 2 列:
TC_14TeV_NLO
1000 1.51100e+01 6.2e-03 4.1e-02%
2000 7.36556e-01 4.4e-04 5.9e-02%
3000 7.85092e-02 5.1e-05 6.5e-02%
4000 1.17810e-02 7.4e-06 6.3e-02%
5000 2.39873e-03 1.3e-06 5.2e-02%
6000 7.18132e-04 2.7e-07 3.7e-02%
7000 3.10281e-04 8.1e-08 2.6e-02%
8000 1.67493e-04 3.3e-08 1.9e-02%
9000 1.01369e-04 2.2e-08 2.2e-02%
10000 6.54776e-05 1.6e-08 2.4e-02%
TC_13TeV_LO
1000 1.04906e+01 1.7e-03 1.7e-02%
2000 4.53170e-01 8.1e-05 1.8e-02%
3000 4.25722e-02 7.9e-06 1.9e-02%
4000 5.80036e-03 1.1e-06 1.9e-02%
5000 1.17278e-03 2.1e-07 1.8e-02%
6000 3.82330e-04 6.1e-08 1.6e-02%
7000 1.78036e-04 2.7e-08 1.5e-02%
8000 9.91945e-05 1.9e-08 1.9e-02%
9000 6.05766e-05 1.6e-08 2.6e-02%
10000 3.92631e-05 1.2e-08 3.0e-02%
解决方案
对于您的示例文件,您可以这样做:
import pandas as pd
#read in first set of data, start from the beginning, read 10 lines
df1=pd.read_csv('exfile.txt', sep=" ",skiprows=None,nrows=10)
#read in the second set of data, do not start at the beginning of file but skip 11 rows, read the next 10 lines
df2=pd.read_csv('exfile.txt', sep=" ",skiprows=11,nrows=10)
#choose any two cols, for example:
print(df1['TC'])
print(df2['13TeV'])
否则,我建议拆分给每个集合自己的文件,而不是使用 pandas.read_csv 来读取它们。
推荐阅读
- php - MYSQL 连接关系
- azure - 如何与 New-AzureRmResourceGroupDeployment cmdlet 一起传递额外参数
- javascript - 单击 WebGL(画布)中的选定坐标
- r - Rmarkdown:在标签集下添加标题
- variables - VueJS - 在字符串中插入字符串
- javascript - 香草 JavaScript 替换元素
- r - 遍历忽略但保留 R 中的 NA 值的列
- laravel - 在 laravel vue 项目中使用 laravel mix 如何在所有组件中包含 scss 文件?
- dom - 如何将我的功能调制为单独的并行测试?
- python - Django 模板语法错误