python pandas插入列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33139513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:50:55  来源:igfitidea点击:

python pandas insert column

pythoncsvpandas

提问by Hari

I am writing code to insert a new column in a csv file:

我正在编写代码以在 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)

When I run the code, no error was given. When I open the csv file, the new row is not added. I decided to check using python shell:

当我运行代码时,没有给出任何错误。当我打开 csv 文件时,不会添加新行。我决定使用 python shell 检查:

>>>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

Using the python shell, I can see the result updated on the shell only. How do I update it in the CSV file as well?

使用 python shell,我只能看到在 shell 上更新的结果。我如何在 CSV 文件中更新它?

采纳答案by Anand S Kumar

When you do -

当你这样做时——

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

It inserts the newcolumn in the DataFrame df(with all values 1000) in memory. It does not automatically write it back to the csv.

它将new列插入df内存中的 DataFrame 中(所有值均为 1000)。它不会自动将其写回 csv。

For changes you did to the dataframe to be written back to csv, you should use DataFrame.to_csv()method. Example -

对于您对要写回 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)

Also, you should make sure you define the function before you try to call it.

此外,您应该确保在尝试调用之前定义了该函数。