pandas:使用(row,col)索引设置值

duc*_*thd 17 python pandas

pandas 提供了按行和列索引列表查找的功能,

In [49]: index = ['a', 'b', 'c', 'd']

In [50]: columns = ['one', 'two', 'three', 'four']

In [51]: M = pandas.DataFrame(np.random.randn(4,4), index=index, columns=columns)

In [52]: M
Out[52]: 
        one       two     three      four
a -0.785841 -0.538572  0.376594  1.316647
b  0.530288 -0.975547  1.063946 -1.049940
c -0.794447 -0.886721  1.794326 -0.714834
d -0.158371  0.069357 -1.003039 -0.807431

In [53]: M.lookup(index, columns) # diagonal entries
Out[53]: array([-0.78584142, -0.97554698,  1.79432641, -0.8074308 ])
Run Code Online (Sandbox Code Playgroud)

我想使用相同的索引方法来设置M元素.我怎样才能做到这一点?

Eze*_*ick 21

自从这个答案写完以来已经过了多年,所以我可能会贡献一点点.随着pandas的重构,尝试在一个位置设置一个值

M.iloc[index][col]
Run Code Online (Sandbox Code Playgroud)

可能会向您发出有关尝试在切片中设置值的警告.

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
Run Code Online (Sandbox Code Playgroud)

在0.21之后的pandas版本中,正确的" pythonic "方式现在是pandas.DataFrame.at运算符

看起来像这样:

M.at[index,col] = new_value
Run Code Online (Sandbox Code Playgroud)

旧版本的答案:在旧版本中执行此操作的更"pythonic"方法是使用pandas.DataFrame.set_value指令.请注意,此指令返回结果DataFrame.

M.set_value(index,column,new_value)
Run Code Online (Sandbox Code Playgroud)

我只是想在找出可以由.iloc或.ix方法生成的警告的来源之后发布这个.

set_value方法也适用于多索引DataFrames,方法是将索引的多个级别作为元组放入(例如用(col,subcol)替换列)


rep*_*cus 18

我不确定我是否关注你,但你是否DataFrame.ix选择/设置个别元素:

In [79]: M
Out[79]: 
        one       two     three      four
a -0.277981  1.500188 -0.876751 -0.389292
b -0.705835  0.108890 -1.502786 -0.302773
c  0.880042 -0.056620 -0.550164 -0.409458
d  0.704202  0.619031  0.274018 -1.755726

In [75]: M.ix[0]
Out[75]: 
one     -0.277981
two      1.500188
three   -0.876751
four    -0.389292
Name: a

In [78]: M.ix[0,0]
Out[78]: -0.27798082190723405

In [81]: M.ix[0,0] = 1.0

In [82]: M
Out[82]: 
        one       two     three      four
a  1.000000  1.500188 -0.876751 -0.389292
b -0.705835  0.108890 -1.502786 -0.302773
c  0.880042 -0.056620 -0.550164 -0.409458
d  0.704202  0.619031  0.274018 -1.755726

In [84]: M.ix[(0,1),(0,1)] = 1

In [85]: M
Out[85]: 
        one       two     three      four
a  1.000000  1.000000 -0.876751 -0.389292
b  1.000000  1.000000 -1.502786 -0.302773
c  0.880042 -0.056620 -0.550164 -0.409458
d  0.704202  0.619031  0.274018 -1.755726
Run Code Online (Sandbox Code Playgroud)

您还可以按索引切片:

In [98]: M.ix["a":"c","one"] = 2.0

In [99]: M
Out[99]: 
        one       two     three      four
a  2.000000  1.000000 -0.876751 -0.389292
b  2.000000  1.000000 -1.502786 -0.302773
c  2.000000 -0.056620 -0.550164 -0.409458
d  0.704202  0.619031  0.274018 -1.755726
Run Code Online (Sandbox Code Playgroud)

  • 这将设置单个元素,但是给定(行,索引,值)对的列表,是否有任何简单的方法可以一次设置它们? (2认同)