如何为 Pandas DataFrame 的列设置值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43074814/
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
How can I set values to a column of pandas DataFrame?
提问by PuDu
For example,
例如,
I got a df
like:
我有一个df
喜欢:
x y
A 1 1
B 2 2
C 3 3
I want to change column 'y' values like this:
我想像这样更改“y”列的值:
x y
A 1 56
B 2 45
C 3 34
I had the values in an array a = [56, 45, 34]
我有一个数组中的值 a = [56, 45, 34]
I can change the values using .set_value:
我可以使用 .set_value 更改值:
df.set_value('A', 'y', a[0])
df.set_value('B', 'y', a[1])
df.set_value('C', 'y', a[2])
But if df
is array, I can do:
但如果df
是数组,我可以这样做:
df[:, 1] = a
Is there a way like the above for setting values to a column of DataFrame?
有没有像上面那样为DataFrame的列设置值的方法?
回答by Yeile
You can try:
你可以试试:
df.loc[:, 'Y'] = a
This should set (all index, column 'Y') of df to Array a, without the SettingWithCopyWarningmessage. This is also the recommended way according to pandas-doc.
这应该将 df 的(所有索引,列“Y”)设置为 Array a,而没有SettingWithCopyWarning消息。这也是pandas-doc推荐的方式。
回答by Sayali Sonawane
Creating dataframe:
创建数据框:
df
Out[]:
x y
A 1 1
B 2 2
C 3 3
You can use iloc function and pass array to it as follows:
您可以使用 iloc 函数并将数组传递给它,如下所示:
df['y'].iloc[0:3]=[56, 45, 34]
df
Out[]:
x y
A 1 56
B 2 45
C 3 34
回答by A.Kot
You just need the following:
您只需要以下内容:
df['Y'] = a