使用Pandas将TXT转为浮点型DataFrame并绘制散点图遇错求助
Hey there! Let's get this scatter plot working for you. The root issue here is exactly what you suspected: your Xpos and Ypos columns are being stored as string (object) types instead of numeric values, so Pandas can't plot them. Here's a step-by-step fix:
1. Clean up your data import first
First, let's make sure we're reading the data correctly—especially handling missing values and any extra whitespace around your separator (|), which is a common culprit for string-type columns:
import pandas as pd # Adjust na_values to match the placeholder used for missing data in your file (e.g., '--', 'NA', or empty strings) df = pd.read_csv( 'data.txt', sep='\s*\|\s*', # Matches '|' with any number of spaces before/after it skiprows=44, na_values=['--', ''], # Replace with whatever marks missing values in u_Vmag/u_B-V engine='python' # Required for regex-based separators )
The sep='\s*\|\s*' fixes cases where your data has spaces around the | (like 123 | 456), which often causes Pandas to read values with extra spaces (making them unconvertible to numbers).
2. Convert Xpos and Ypos to numeric types
Now let's explicitly convert the columns you need for plotting to floats. We'll use pd.to_numeric with errors='coerce' to turn any unconvertible values into NaN (which won't break plotting):
# Convert target columns to numeric df['Xpos'] = pd.to_numeric(df['Xpos'], errors='coerce') df['Ypos'] = pd.to_numeric(df['Ypos'], errors='coerce') # Verify the type change print(df.info())
You should see Xpos and Ypos listed as float64 instead of object now.
3. Plot your scatter graph
Once the columns are numeric, plotting should work perfectly. You can use either Pandas' built-in plot function or Matplotlib for more control:
Option 1: Pandas built-in plot
df.plot.scatter(x='Xpos', y='Ypos', title='Xpos vs Ypos Scatter Plot')
Option 2: Matplotlib (customizable)
import matplotlib.pyplot as plt plt.scatter(df['Xpos'], df['Ypos']) plt.xlabel('Xpos') plt.ylabel('Ypos') plt.title('Xpos vs Ypos Scatter Plot') plt.show()
Quick troubleshooting tips
- If conversion still fails, check raw values with
df['Xpos'].head(10)—look for extra characters like spaces, commas, or non-numeric symbols (e.g.,'123.45 'or'N/A'). Strip whitespace first withdf['Xpos'] = df['Xpos'].str.strip()before converting. - If some rows have completely missing
Xpos/Ypos, drop them withdf = df.dropna(subset=['Xpos', 'Ypos'])to avoid empty plot warnings.
内容的提问来源于stack exchange,提问作者Kat

