pd.saveto和pd.read_csv添加标题和索引列

时间:2018-11-09 13:34:36

标签: python pandas csv

我有一个这样保存的数据框:

Y_train_1.head()

0    4691.0
1    4661.0
2    4631.0
3    4601.0
4    4571.0

Y_train_1.to_csv("Y_train.csv", sep='\t', decimal=',')

然后我再次这样阅读:

Y_train = pd.read_csv("Y_train.csv", sep='\t', decimal=',', index_col=None, header=None))
Y_train.head()

enter image description here

使用

Y_train = pd.read_csv("Y_train.csv", sep='\t', decimal=',', index_col=[0], header=None)

我还是得到像这样的数据框,与以前不同吗?

enter image description here

如何获得与以前相同的数据框?

usi

谢谢,R

1 个答案:

答案 0 :(得分:2)

如果使用Series,请添加参数squeeze=True

print (type(Y_train_1))
<class 'pandas.core.series.Series'>

print (Y_train_1)
0    4691.0
1    4661.0
2    4631.0
3    4601.0
4    4571.0
dtype: float64

Y_train_1.to_csv("Y_train.csv", sep='\t', decimal=',', header=None)
Y_train = pd.read_csv("Y_train.csv", 
                      sep='\t', 
                      decimal=',', 
                      index_col=[0], 
                      squeeze=True, 
                      header=None)
print (Y_train)
0
0    4691.0
1    4661.0
2    4631.0
3    4601.0
4    4571.0
Name: 1, dtype: float64

Y_train_1.to_csv("Y_train.csv", sep='\t', decimal=',', index=False, header=None)
Y_train = pd.read_csv("Y_train.csv", sep='\t', decimal=',', squeeze=True, header=None)
print (Y_train)
0    4691.0
1    4661.0
2    4631.0
3    4601.0
4    4571.0
Name: 0, dtype: float64