2017-10-18 77 views
0

csv文件看起來像:CSV文件給出的字符串

"(-0.16192019, -0.007456851, 0.08841695)","(-0.10439591, 0.024501082, 0.12783173)","(-0.05965481, 0.049002163, 0.12144014)",... 

,但我不希望引號。

我寫的功能爲:

for j in range(len(sensor_data)): 
    with open(names[j] + "P" + str(i) + ".csv", "wb") as f: 
     writer = csv.writer(f) 
     writer.writerows(sensor_data[j]) 

sensor_data[j]是這樣的:

gyro.append((float(merge.iloc[j, 2]), float(merge.iloc[j, 3]), float(merge.iloc[j, 4]))) if merge.iloc[j, 0] == 'Gyroscope' \ 
      else acc.append((float(merge.iloc[j, 2]), float(merge.iloc[j, 3]), float(merge.iloc[j, 4]))) 

爲什麼沒有打印出花車,而不是字符串的元組的元組?

merge = pd.read_csv(final_user_study_path + "/P" + str(i) + "/DataCollection/data/merge.csv") 

合併的樣子:

Gyroscope,50958,-0.3387541,0.014913702,0.05965481 
Gyroscope,50978,-0.23009712,0.03621899,0.044741105 
LinearAcceleration,50979,-0.09891046,0.119261175,-0.108936176 
Gyroscope,50998,-0.1768339,0.066046394,0.040480047 
LinearAcceleration,50999,-0.0863409,0.18240824,-0.07152677 

類型所有這些值都是字符串。

我想:

(-0.16192019, -0.007456851, 0.08841695),(-0.10439591, 0.024501082, 0.12783173),(-0.05965481, 0.049002163, 0.12144014),... 
+0

其中'merge'定義了嗎? –

+0

已編輯的問題陳述 – dirtysocks45

+0

編輯問題陳述 – dirtysocks45

回答

1

要加上引號在需要的時候停止csv.writer()(因爲它發現在單元格的分隔符),加上quoting參數如下:

writer = csv.writer(f, quoting=csv.QUOTE_NONE) 

見CSV文檔:csv.QUOTE_NONE

這將是更好的解開元組,使他們各自正確地得到自己的單元格w沒有任何額外的括號。這可能會使用itertools.chain.from_iterable()來完成,以將所有元組合併到一個列表中。例如:

from itertools import chain 

row = [(-0.16192019, -0.007456851, 0.08841695), (-0.10439591, 0.024501082, 0.12783173), (-0.05965481, 0.049002163, 0.12144014)] 

print row 
print list(chain.from_iterable(row)) 

這將顯示:

[(-0.16192019, -0.007456851, 0.08841695), (-0.10439591, 0.024501082, 0.12783173), (-0.05965481, 0.049002163, 0.12144014)] 
[-0.16192019, -0.007456851, 0.08841695, -0.10439591, 0.024501082, 0.12783173, -0.05965481, 0.049002163, 0.12144014] 

正如你所看到的,第二行顯示的是所有的記錄都被夷爲平地到一個列表。

+0

如果我想元組具有某些標籤,例如(0,1,2) [0,1,2]。我想在csv。 – dirtysocks45

+1

中的每一個單獨的列中使用'.writerow()'來寫一行,每行使用'chain.from_iterable( )'把元組扁平化爲一個列表 –

+1

我刪除了我的評論,因爲我意識到你的解決方案給了我所需要的東西。 – dirtysocks45