[英]Python read csv file with different number of rows
我有一个具有以下格式的 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 的内容。 我怎样才能做到这一点?
tuples
list
[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()
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()
x
和y
合并为一个组# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.