使用numpy数组修改 pandas 数据框值 [英] Modify pandas dataframe values with numpy array

查看:75
本文介绍了使用numpy数组修改 pandas 数据框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用numpy数组[相同大小]修改熊猫数据框的values字段.像这样的东西不起作用

I'm trying to modify the values field of a pandas data frame with a numpy array [same size]. something like this does not work

import pandas as pd
# create 2d numpy array, called arr
df = pd.DataFrame(arr, columns=some_list_of_names)
df.values = myfunction(arr)

还有其他选择吗?

推荐答案

.values属性通常是一个副本-特别是对于混合dtypes(因此不能保证分配成功)-在较新版本的pandas中,这会引发).

The .values attribute is often a copy - especially for mixed dtypes (so assignment to it is not guaranteed to work - in newer versions of pandas this will raise).

您应该分配给特定的列(注意顺序很重要).

You should assign to the specific columns (note the order is important).

df = pd.DataFrame(arr, columns=some_list_of_names)
df[some_list_of_names] = myfunction(arr)


示例(以熊猫0.15.2为单位):


Example (in pandas 0.15.2):

In [11]: df = pd.DataFrame([[1, 2.], [3, 4.]], columns=['a', 'b'])

In [12]: df.values = [[5, 6], [7, 8]]
AttributeError: can't set attribute

In [13]: df[['a', 'b']] = [[5, 6], [7, 8]]

In [14]: df
Out[14]:
   a  b
0  5  6
1  7  8

In [15]: df[['b', 'a']] = [[5, 6], [7, 8]]

In [16]: df
Out[16]:
   a  b
0  6  5
1  8  7

这篇关于使用numpy数组修改 pandas 数据框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆