Pandas:如何编辑 .csv 文件列中的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38719184/
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-09-14 01:43:50  来源:igfitidea点击:

Pandas: how to edit values in a column of a .csv file?

pythonpandas

提问by TRK

I have a .csv file which looks as follows:link

我有一个 .csv 文件,如下所示:link

I want to open this file using pandas and edit the column Coordinateby adding a constant value of 756 to each value in it. Finally, I want the changes to be reflected in the .csv file.

我想使用 Pandas 打开这个文件,并通过向其中的每个值添加一个常量值 756 来编辑列Coordinate。最后,我希望更改反映在 .csv 文件中。

How do I do that?

我怎么做?

Edit: What I had been doing is as follows (@EdChum):

编辑:我一直在做的事情如下(@EdChum):

df = pd.read_csv('C:/TestBook1.csv')
df = df[['Coordinate','Speed']]

Coord = df['Coordinate']
Coord = Coord + 756

This is where I was going wrong. From here it would have been a messy affair to save changes into the .csv file.

这是我出错的地方。从这里开始,将更改保存到 .csv 文件将是一件很麻烦的事情。

回答by ??????

you can also type:

你也可以输入:

df["Coordinate"] = df["Coordinate"] + 756

回答by TRK

@EdChum: Thanks for your comment. It kind of fired me up. I was unnecessarily complicating things for myself. Following is what I did:

@EdChum:感谢您的评论。这有点让我兴奋。我给自己不必要地复杂化了。以下是我所做的:

df = pd.read_csv('C:/TestBook1.csv')
df = df[['Coordinate','Speed']]

df['Coordinate']+=756
df.to_csv('C:/TestBook1.csv')

Initially I was loading all the values of the column into a variable and trying to find a way to save it. After your comment I thought of experimenting and I am glad that it worked for me.

最初我将列的所有值加载到一个变量中并试图找到一种方法来保存它。在您发表评论后,我想到了尝试,我很高兴它对我有用。

回答by Sayali Sonawane

Define path where csv file is located

定义csv文件所在的路径

Location = r'C:\'
df = pd.read_csv(Location,header=None)
df["Coorinate"].values +756

Do not forget to import pandas package

不要忘记导入pandas包

import pandas as pd