gpt4 book ai didi

python - 使用 nrows 和 skiprows 读取 pandas 数据框时保留列名

转载 作者:行者123 更新时间:2023-11-28 18:33:47 24 4
gpt4 key购买 nike

我正在通过使用变量 nbr_rows_to_readnbr_rows_to_skip 定义要读取的行数和要跳过的行数来读取大数据文件

data_df = pd.read_csv(data_file, delimiter="|", nrows=nbr_rows_to_read,
skiprows=nbr_rows_to_skip,
dtype={'col1':object,'col2':object,'col3':object, 'col4': object})

问题是,列名只在跳过 0 行的第一个 block 中读取。对于其他 block ,我得到第一行定义为列名的值。如何将列名保留在其他 block 中?

最佳答案

IIUC 您可以在 read_csv 的参数 skiprows 中使用 list 数字代替 integer :

skiprows : list-like or integer, default None

Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file

演示:

import pandas as pd
import io

#test data
temp=u"""id|col1|col2|col3
1|13|15|0
1|13|15|1
1|13|15|2
1|12|15|3
1|13|15|4
1|12|15|5
1|12|15|6
2|18|15|7"""


#skip first data rows, keep header
nbr_rows_to_skip = range(1, 2)
nbr_rows_to_read = 6

data_df = pd.read_csv(io.StringIO(temp), delimiter="|", nrows=nbr_rows_to_read, skiprows=nbr_rows_to_skip, dtype={'col1':object,'col2':object,'col3':object, 'col4': object})
print data_df
# id col1 col2 col3
#0 1 13 15 1
#1 1 13 15 2
#2 1 12 15 3
#3 1 13 15 4
#4 1 12 15 5
#5 1 12 15 6

关于python - 使用 nrows 和 skiprows 读取 pandas 数据框时保留列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34335548/

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