2015-10-15 177 views
1

我寫的代碼在CSV文件中插入一個新列:蟒蛇大熊貓插入列

import sys,os,csv,glob 
dir = os.path.dirname(__file__) 

import pandas as pd 

updatecsv() 

def updatecsv(): 

    files = 'example.cs' 
    df = pd.read_csv(files) 
    df = df.convert_objects(convert_numeric=True) 
    #until here, the code is running fine 
    #now i wanted to add a new column in a specific index with all value =10   
    df.insert(2,'new',1000) 

當我運行的代碼,被賦予任何錯誤。當我打開CSV文件,新行不會被添加。我決定使用Python外殼檢查:

>>>files = 'example.csv' 
>>>df = pd.read_csv(files) 
>>>df = df.convert_objects(convert_numeric=True) 
>>>df 
    A B C D 
0 1 2 3 4 
1 5 6 7 8 
2 9 10 11 12 
df['new']=13 
>>>df 
    A B C D new 
0 1 2 3 4 13 
1 5 6 7 8 13 
2 9 10 11 12 13 
>>>df['new'] = df['new'] +1 
>>>df 
    A B C D new 
0 1 2 3 4 14 
1 5 6 7 8 14 
2 9 10 11 12 14 
>>>df.insert(2,'win',22) 
>>>df 
    A B win C D new 
0 1 2 22 3 4 14 
1 5 6 22 7 8 14 
2 9 10 22 11 12 14 

使用Python外殼,我可以看到更新僅在外殼的結果。如何在CSV文件中對其進行更新?

回答

3

當你這樣做 -

df.insert(2,'new',1000) 

它插入在數據幀dfnew欄(與所有值1000)在內存中。它不會自動將其寫回CSV。

對於您對要寫回csv的數據框做的更改更改,應該使用DataFrame.to_csv()方法。示例 -

def updatecsv(): 
    files = 'example.cs' 
    df = pd.read_csv(files) 
    df = df.convert_objects(convert_numeric=True) 
    #until here, the code is running fine 
    #now i wanted to add a new column in a specific index with all value =10   
    df.insert(2,'new',1000) 
    df.to_csv(files) 

另外,您應該確保在嘗試調用函數之前先定義該函數。