2016-04-26 54 views
0

我有一个简单的ndarray,我想导出到csv,即我只想要一列逗号分隔值。原因是我必须根据数组中的值手动对另一个df的值进行排序。我的数据如下:pandas:export ndarray to csv

url='https://raw.githubusercontent.com/108michael/ms_thesis/master/rgdpconc.csv' 
result=pd.read_csv(url, index_col=0) 
uniq=result.IndustryClassification.unique() 
#uniq.to_csv('rgdp_uniq_indstry_class.csv') 
uniq #this is my ndarray 

回答

3

我想你需要创建DataFrame然后把它写入to_csv

df = pd.DataFrame({'unique':uniq}) 
df.to_csv('rgdp_uniq_indstry_class.csv') 

或者Seriesto_csv

s = pd.Series(uniq) 
s.to_csv('rgdp_uniq_indstry_class.csv') 
+1

Bingo!再次感谢! –

+0

很高兴能帮到你!祝你好运! – jezrael

4

创建ndarray到熊猫数据帧,然后使用to_csv大熊猫方法。

uniq = pd.Dataframe({'var1':uniq}) 
uniq.to_csv('name_of_file') 

缺省分隔符为',',但你可以指定一个又一个与参数SEP像这样

uniq.to_csv('name_of_file', sep =' ') #use whitespace for example 

同时请记住,如果你有兴趣在维护float精度参数fmt是非常重要的。例如。

uniq.to_csv('name_of_file', fmt='%1.3f') 
+1

'Series.unique()'返回一个numpy数组,所以这不起作用。 –

+1

是的,对不起,我假设uniq变量是一个数据帧 –

1

你不能给一个ndarray对象to_csv.Because他们不这样做有这样一个方法。所以将其转换为一个熊猫数据框并给出一个csv输出。

import pandas as pd 

df = pd.DataFrame(uniq,columns=['suitable column name']) 
df.to_csv('path+csvfilename',index=False) #### index=False will remove the extra index column in the csv