我正在使用 numpy.genfromtxt()
读取 CSV 文件,并且我想将 header 与 header 下方的数据分开保存。
我知道 skip_header=1
参数允许我跳过 header ,但是在这种情况下, header 会丢失,但我想保存它。我尝试使用 skip_footer
参数,这样它就会跳过标题下面的所有内容,并通过将 skip_footer
设置为小于 1 来仅保留标题CSV 文件的长度或 skip_footer=(len('filename.csv')-1)
。代码可以运行,但没有给出正确的输出。不知何故,numpy.genfromtxt()
并没有按照我想象的方式计算 CSV 文件的行数。
header = numpy.genfromtxt('filename.csv', delimiter=',', skip_footer=(len('filename.csv')-1))
我希望只得到标题作为一维 NumPy 数组,但我得到了类似于整个数组的东西:
[[ nan nan nan ... nan nan nan]
[2.016e+03 1.000e+00 1.000e+00 ... 1.165e+01 6.999e+01 1.000e+00]
[2.016e+03 1.000e+00 1.000e+00 ... 8.000e+00 5.430e+01 1.000e+00]
...
[2.016e+03 6.000e+00 3.000e+01 ... 0.000e+00 4.630e+01 2.000e+00]
[2.016e+03 6.000e+00 3.000e+01 ... 8.750e+00 5.255e+01 1.000e+00]
[2.016e+03 6.000e+00 3.000e+01 ... 8.880e+00 5.822e+01 1.000e+00]]
我想只保留 nan
顶行中的内容。
最佳答案
解决方案:
header = np.genfromtxt('filename.csv', delimiter=',', dtype=str, max_rows=1)
print(header)
输出:
['pickup_year' 'pickup_month' 'pickup_day' 'pickup_dayofweek'
'pickup_time' 'pickup_location_code' 'dropoff_location_code'
'trip_distance' 'trip_length' 'fare_amount' 'fees_amount' 'tolls_amount'
'tip_amount' 'total_amount' 'payment_type']
关于python-3.x - 使用 `numpy.genfromtxt()` 从 CSV 文件保存 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56516937/