2016-04-26 58 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