2016-09-05 38 views
4

我想使用下面的代码使用Pandas中的排序函数对CSV文件中的数据进行排序。原始文件中有229行。但排序的输出是245行,因为字段中的一些数据打印在下一行中,而某些行没有任何值。在熊猫中排序函数,返回凌乱的数据

sample=pd.read_csv("sample.csv" , encoding='latin-1', skipinitialspace=True) 
sample_sorted = sample.sort_values(by = ['rating']) 
sample_sorted.to_csv("sample_sorted.csv") 

我认为,这个问题的发生是因为在某些细胞中的数据是由产生新的线路输入。例如,这是原始文件中单元格的内容。当我对原始文件进行排序时,第二行打印在一行中,第三行和第二行之间留空。

"Side effects are way to extreme. 



E-mail me if you have experianced the same things." 

有什么建议吗?谢谢 !

+1

你可以发布:'print(sample.shape)'的输出吗? – MaxU

+0

@MaxU,print(sample.shape)的输出是(229,10) – Mary

+0

@Merlin,我认为它可能是文件内部的其他字符,例如阿拉伯字符。是的,文件有标题。 – Mary

回答

2

您可以尝试删除问题列中的换行符。

sample=pd.read_csv("sample.csv" , encoding='latin-1', skipinitialspace=True) 
sample["problem_column"] = (sample["problem_column"]. 
          apply(lambda x: " ".join([word for word in x.split()]) 
          ) 

看看是否有帮助。很难看出为什么没有可重复的样本发生这种情况。