简体   繁体   English

如何每隔一行读取CSV文件

[英]How to read a CSV file every other row

how do I take from a CSV file data every 2 rows? 如何每2行从CSV文件中获取数据?

For example if I have a file that looks this 例如,如果我有一个看起来像这样的文件

  0   1
0 23  34
1 45  45
2 78  16
3 110 78
4 48  14
5 76  23
6 55  33
7 12  13
8 18  76

how can iterate and extract every 2nd row to get something like this and append in a new dataframe? 如何迭代和提取第二行以获得类似的内容并追加到新的数据框中?

0 23  34
2 78  16
4 48  14
6 55  33
8 18  76

Thank you! 谢谢!

Use the skiprows parameter of read_csv : 使用skiprows的参数read_csv

To keep even rows: 要保持偶数行:

pd.read_csv('file.csv', skiprows=lambda x: (x != 0) and not x % 2)

To keep odd rows: 要保留奇数行:

pd.read_csv('file.csv', skiprows=lambda x: x % 2)

Note that the header is included in skiprows , which is why the x != 0 is needed in the even example. 请注意,标头包含在skiprows ,这就是为什么在偶数示例中需要x != 0原因。

Example: 例:

In [1]: import pandas as pd
   ...: from io import StringIO
   ...:
   ...: data = """A,B
   ...: a,1
   ...: b,2
   ...: c,3
   ...: d,4
   ...: e,5
   ...: """

In [2]: pd.read_csv(StringIO(data))
Out[2]:
   A  B
0  a  1
1  b  2
2  c  3
3  d  4
4  e  5

In [3]: pd.read_csv(StringIO(data), skiprows=lambda x: (x != 0) and not x % 2)
Out[3]:
   A  B
0  a  1
1  c  3
2  e  5

In [4]: pd.read_csv(StringIO(data), skiprows=lambda x: x % 2)
Out[4]:
   A  B
0  b  2
1  d  4

you could read them all into memory with numpy and store every other row: 您可以使用numpy将它们全部读取到内存中并存储每隔一行:

import numpy as np
import pandas as pd

data = np.loadtxt(filename)
data = pd.DataFrame(data[::2])

The last bit, [::2] , means "take every second element". 最后一位[::2]表示“每隔第二个元素”。

Personally, I think the easiest answer (if you only want even-numbered rows) is to do: 就我个人而言,我认为最简单的答案是(如果您只想要偶数行):

import pandas as pd
df = pd.read_csv('csv_file.csv')
rows_we_want = [row for i,row in enumerate(df.index) if not i % 2]
df_new = df.loc[rows_we_want]

enumerate() is a powerful function in Python and "if not i % 2" is only True when the row number (i) is even. enumerate()是Python中的强大功能,并且当行号(i)为偶数时,“ if if i%2”仅是True。 You could delete the "not" if you want the odd-numbered rows instead. 如果要改用奇数行,则可以删除“ not”。 I think this approach is easier than reading in the file line-by-line, though there could be scalability issues with this if your file is extremely large. 我认为这种方法比逐行读取文件更容易,尽管如果文件很大,则可能存在可伸缩性问题。 Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM