Python 3.6.5中DataFrame对象类型数值转long及绘图问题求助
Hey Kevin! Let's get those Volume and Market Cap columns plotting properly. The root issue here is that those columns are stored as object (string) types because of the commas in the numbers—Pandas can't plot strings directly, so we need to convert them to numeric formats first.
Step 1: Confirm the Data Type Problem
First, let's verify the data types of your columns to be sure:
print(df.dtypes)
You'll see Volume and Market Cap listed as object instead of int64 or float64.
Step 2: Convert String Columns to Numeric Values
We need to remove the commas and convert the columns to a numeric type. Here are two reliable methods:
Method 1: Direct String Replacement + Type Cast
This works if all values in the columns follow the same comma-separated format:
# Clean and convert Volume column df['Volume'] = df['Volume'].str.replace(',', '').astype('int64') # Clean and convert Market Cap column df['Market Cap'] = df['Market Cap'].str.replace(',', '').astype('int64')
Method 2: Robust Conversion with pd.to_numeric
If there's a chance of invalid values (like non-numeric strings), use this method to handle errors gracefully:
df['Volume'] = pd.to_numeric(df['Volume'].str.replace(',', ''), errors='coerce') df['Market Cap'] = pd.to_numeric(df['Market Cap'].str.replace(',', ''), errors='coerce')
The errors='coerce' parameter will turn any unconvertable values into NaN, which you can then clean up with df.dropna() or df.fillna() if needed.
Step 3: Plot Your Data
Now that the columns are numeric, your plotting code should work perfectly:
df.plot(x='Date', y='Volume', kind='line') # Or your preferred plot type df.plot(x='Date', y='Market Cap', kind='line')
Pro Tip for Future Data Imports
To avoid this issue entirely when loading your data, use the thousands parameter in pd.read_csv() to tell Pandas to parse commas as thousand separators:
df = pd.read_csv('your_data_file.csv', thousands=',')
This will load Volume and Market Cap as numeric types right from the start, saving you post-processing steps.
内容的提问来源于stack exchange,提问作者Kevin Riordan

