gpt4 book ai didi

python - 为 read_csv 中的 Pandas 索引列指定转换器

转载 作者:行者123 更新时间:2023-12-02 15:50:11 26 4
gpt4 key购买 nike

我正在尝试读取索引列中包含十六进制数字的 CSV 文件:

InputBits, V0, V1, V2, V3
7A, 0.000594457716, 0.000620631282, 0.000569834178, 0.000625374384,
7B, 0.000601155649, 0.000624282078, 0.000575955914, 0.000632111367,
7C, 0.000606026872, 0.000629149805, 0.000582689823, 0.000634561234,
7D, 0.000612115902, 0.000634625998, 0.000584526357, 0.000638235952,
7E, 0.000615769413, 0.000637668328, 0.000590648093, 0.00064987256,
7F, 0.000620640637, 0.000643144494, 0.000594933308, 0.000650485013,

我可以使用以下代码来做到这一点:

df = pd.read_csv('data.csv', index_col=False,
converters={'InputBits': lambda x: int(x, 16)})
df.set_index('InputBits', inplace=True)

问题是这看起来过于笨拙。有没有办法做相当于以下的事情?

df = pd.read_csv('data.csv', converters={'InputBits': lambda x: int(x, 16)})

此操作失败,因为 InputBits 现在是第一个数据列

ValueError: invalid literal for int() with base 16: ' 0.000594457716'

最佳答案

正如 @root 在这里指出的,此示例中的问题是标题与列名和列值未对齐,这些列名和列值都有一个尾随逗号。事实上,the documentation处理这个特定的场景:

If you have a malformed file with delimiters at the end of each line, you might consider index_col=False to force pandas to not use the first column as the index (row names)

这里的解决方案首先运行

sed -i 's/, \r$//' data.csv

去掉最后的逗号(和 Windows 行结尾)。然后,预期的命令几乎可以开箱即用:

pd.read_csv('data.csv', index_col='InputBits',
converters={'InputBits': lambda x: int(x, 16)})

关于python - 为 read_csv 中的 Pandas 索引列指定转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40347377/

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