我知道 skiprows 允许您传递包含要跳过的行索引的列表。但是,我有要保留的行的索引。
假设我的 cvs 文件在数百万行中看起来像这样:
A B
0 1 2
1 3 4
2 5 6
3 7 8
4 9 0
Run Code Online (Sandbox Code Playgroud)
我想加载的索引列表只有 2,3,所以
index_list = [2,3]
Run Code Online (Sandbox Code Playgroud)
skiprows 函数的输入是 [0,1,4]。但是,我只有 [2,3] 可用。
我正在尝试类似的东西:
pd.read_csv(path, skiprows = ~index_list)
Run Code Online (Sandbox Code Playgroud)
但没有运气..有什么建议吗?
谢谢,我感谢所有的帮助,
wcy*_*cyn 10
您可以在skiprows参数中传入一个 lambda 函数。例如:
rows_to_keep = [2,3]
pd.read_csv(path, skiprows = lambda x: x not in rows_to_keep)
Run Code Online (Sandbox Code Playgroud)
您可以在此处的文档中阅读更多相关信息
我认为你需要先找到行数,就像这样。
num_lines = sum(1 for line in open('myfile.txt'))
Run Code Online (Sandbox Code Playgroud)
然后你需要删除的索引index_list:
to_exclude = [i for i in num_lines if i not in index_list]
Run Code Online (Sandbox Code Playgroud)
然后加载您的数据:
pd.read_csv(path, skiprows = to_exclude)
Run Code Online (Sandbox Code Playgroud)