Python读取具有不同行数的csv文件

2024-05-13 16:38:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件,格式如下

x1,y1,x2,y2,x3,y3
1,1,2,2,6.5,7.5
2,2,-1,-1,,
,,-2,-3,,
,,-5,-5,,

例如,我想绘制(x1,y1)(x2,y2)(x3,y3)

rd1 = some_csv_reader('filename.csv')
matplotlib.pyplot.plot(rd1[:,0],rd1[:,1],rd1[:,2],rd1[:,3])

我尝试使用pandas.read_csv(),但它将nan作为空条目pandas.fwf()不分隔列。我想在读取数组本身时排除数组中的任何空位置,而不是使用类似https://stackoverflow.com/a/11453235/11638153的东西。我该怎么做


Tags: 文件csvpandas格式绘制some数组reader
1条回答
网友
1楼 · 发布于 2024-05-13 16:38:54
  • 如果要打印数据,请选择两个一组的列,然后打印每组。
    • 列表理解创建了listtuples
      • [Index(['x1', 'y1'], dtype='object'), Index(['x2', 'y2'], dtype='object'), Index(['x3', 'y3'], dtype='object')]
import pandas as pd
import matplotlib.pyplot as plt

# read the csv
df = pd.read_csv('test.csv')

# select ever two columns and plot them
N = 2  # number of consecutive columns to combine
for d in [df.columns[n:n+N] for n in range(0, len(df.columns), N)]:
    x, y = d
    plt.scatter(x, y, data=df, label=y)
plt.legend()
  • 请注意,有些点是重叠的

enter image description here

作为直线图

  • 如果需要,使用标记帮助区分数据
markers = ['o', '*', '+']

N = 2
for i, d in enumerate([df.columns[n:n+N] for n in range(0, len(df.columns), N)]):
    x, y = d
    plt.plot(x, y, '', marker=markers[i], data=df, label=y)
plt.legend()

enter image description here

将每组xy组合成一个组

# select each group of two columns and append the dataframe to the list
df_list = list()
N = 2
for d in [df.columns[n:n+N] for n in range(0, len(df.columns), N)]:
    d = df[d]
    d.columns = ['x', 'y']  # rename columns
    df_list.append(d)

# concat the list of dataframes
dfc = pd.concat(df_list)

# clean the dataframe
dfc = dfc.dropna().drop_duplicates().sort_values('x').reset_index(drop=True)

# display(dfc)
     x    y
0 -5.0 -5.0
1 -2.0 -3.0
2 -1.0 -1.0
3  1.0  1.0
4  2.0  2.0
5  6.5  7.5

# plot
plt.plot('x', 'y', '', data=dfc)

enter image description here

相关问题 更多 >