我正在尝试使用numpy数组[相同大小]修改pandas数据框的values字段。像这样的东西不起作用
import pandas as pd
# create 2d numpy array, called arr
df = pd.DataFrame(arr, columns=some_list_of_names)
df.values = myfunction(arr)
任何替代方案?
答案 0 :(得分:10)
.values
属性通常是一个副本 - 特别是对于混合dtypes(因此无法保证它的分配工作 - 在新版本的pandas中会增加)。
您应该分配给特定的列(注意顺序很重要)。
df = pd.DataFrame(arr, columns=some_list_of_names)
df[some_list_of_names] = myfunction(arr)
示例(在熊猫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
答案 1 :(得分:2)
我认为这是您正在寻找的方法:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.applymap.html
将函数应用于要运行的DataFrame 元素,即喜欢为每个系列做map(func,series) 数据帧
示例:
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.random.rand(3,4), columns = list('abcd'))
>>> df
a b c d
0 0.394819 0.662614 0.752139 0.396745
1 0.802134 0.934494 0.652150 0.698127
2 0.518531 0.582429 0.189880 0.168490
>>> f = lambda x: x*100
>>> df.applymap(f)
a b c d
0 39.481905 66.261374 75.213857 39.674529
1 80.213437 93.449447 65.215018 69.812667
2 51.853097 58.242895 18.988020 16.849014
>>>
答案 2 :(得分:0)
希望这很清楚:
import pandas as pd
df = pd.DataFrame(columns=some_list_of_names)
df.loc[:] = arr # use this to replace the values with the numpy array