np.loadtxt报ValueError:无法将日期字符串转为浮点数的解决求助
Alright, let's break down why you're hitting this error and how to fix it quickly.
The problem here is that numpy.loadtxt() tries to convert all columns to floats by default, but your first column is a date string like '2017-07-26'—which can't be turned into a float, hence the ValueError: could not convert string to float: b'2017-07-26'.
Solution 1: Convert Dates to Unix Timestamps (Perfect for Your Tutorial)
Since you're following a tutorial about Unix time and matplotlib, the ideal fix is to use the converters parameter in loadtxt() to turn those date strings into Unix timestamps (floats that play nicely with your numerical data). Here's the code:
import numpy as np from datetime import datetime # Define a function to convert date bytes to Unix timestamps def date_to_unix(date_bytes): # loadtxt reads strings as bytes, so first decode to UTF-8 date_str = date_bytes.decode('utf-8') # Parse the date string and get its Unix timestamp return datetime.strptime(date_str, '%Y-%m-%d').timestamp() L = ['2017-07-26,153.3500,153.9300,153.0600,153.5000,153.5000,12778195.00', '2017-07-25,151.8000,153.8400,151.8000,152.7400,152.7400,18714400.00', '2017-07-24,150.5800,152.4400,149.9000,152.0900,152.0900,21304700.00'] # Use converters to handle the first column (index 0) date, closep, highp, lowp, openp, adj_closep, volume = np.loadtxt( L, delimiter=',', unpack=True, converters={0: date_to_unix} )
This tells loadtxt() to run our date_to_unix function on the first column, turning dates into float-formatted Unix timestamps that work seamlessly with the rest of your data.
Solution 2: Keep Dates as Datetime Objects
If you'd rather retain dates in a human-readable datetime format, you can define a structured dtype for your data:
import numpy as np from datetime import datetime def date_to_datetime(date_bytes): date_str = date_bytes.decode('utf-8') return datetime.strptime(date_str, '%Y-%m-%d') L = ['2017-07-26,153.3500,153.9300,153.0600,153.5000,153.5000,12778195.00', '2017-07-25,151.8000,153.8400,151.8000,152.7400,152.7400,18714400.00', '2017-07-24,150.5800,152.4400,149.9000,152.0900,152.0900,21304700.00'] # Define a structured dtype with datetime and float columns dtype_spec = [ ('date', 'datetime64[D]'), ('closep', float), ('highp', float), ('lowp', float), ('openp', float), ('adj_closep', float), ('volume', float) ] # Load data with the custom dtype data = np.loadtxt(L, delimiter=',', dtype=dtype_spec, converters={0: date_to_datetime}) # Access columns by name date = data['date'] closep = data['closep'] # Repeat for other columns
This keeps dates in a more intuitive format, though unpacking isn't as straightforward as the first method.
Bonus: Simplify with Pandas
If you're open to using pandas (a numpy-based library for tabular data), date parsing becomes even easier:
import pandas as pd from io import StringIO L = ['2017-07-26,153.3500,153.9300,153.0600,153.5000,153.5000,12778195.00', '2017-07-25,151.8000,153.8400,151.8000,152.7400,152.7400,18714400.00', '2017-07-24,150.5800,152.4400,149.9000,152.0900,152.0900,21304700.00'] # Convert string list to a file-like object and read it df = pd.read_csv(StringIO('\n'.join(L)), parse_dates=['date']) # Extract columns easily date = df['date'] closep = df['closep']
But since you're following a numpy-focused tutorial, the first converters method is the best fit for your current workflow.
内容的提问来源于stack exchange,提问作者user1953366

