使用pandas loc / iloc / at / iat / ix获取标量值

时间:2015-11-12 01:08:47

标签: python pandas

我有两个数据帧:df1和df2。我正在使用iterrows迭代df1,并且对于每一行中的特定字段,我正在查看df2以查找与该字段匹配的行,并尝试从SCALAR格式的df2中的该行中提取相应的值。我试图这样做的每一种方式我最终得到另一个数据帧或系列,我不能使用该值作为标量。这是我最近的尝试:

for index, row in df1.iterrows():
    a = row[0]
    b = df2.loc[(df2['name'] == a ), 'weight']
    c = row[1] - b   #this is where error happens
    df1.set_value(index,'wtdif',c)

我收到错误,因为' b'在这种情况下不是标量,如果我在这里打印它是一个它的样子的例子。 '这是在df2中找到的行的索引。关于这一点的另一个令人困惑的部分是我无法指出' b'以任何方式,即使它是一个系列(即b [0]产生错误,b [' weight']等)。

Name: weight, dtype: float64
24    141.5

2 个答案:

答案 0 :(得分:1)

您收到错误是因为b中唯一的索引是24.您可以使用

按位置使用该索引或(更容易)索引
b.iloc[0]

这是新Pandas用户的常见问题。从数据系列或DataFrame中提取数据时,会保留索引。通常,它们不会从0 - >运行。 N-1其中N是系列的长度或DataFrame中的行数。

这会有点http://pandas.pydata.org/pandas-docs/stable/indexing.html,但我承认起初它也让我感到困惑。

答案 1 :(得分:0)

Welp,当我对代码进行更改时,我仍然得到“IndexError:单个位置索引器超出范围”。

你的建议虽然很有意义但确实有效,感谢发帖。我写了一个快速测试脚本来验证修复,事实上它确实起作用了。我会在这里发布这些代码以防其他任何人好奇。

我在这里遗漏了一些东西,我只需继续处理错误以及我的下一个问题应该是什么......

import pandas as pd
import numpy as np

def foo(df1,df2):

    df1['D'] = 0

    for index,row in df1.iterrows():
        name = row[2]  #for some reason name ends up as column 3 in this dataframe rather than column 0?  whatever, not important, but strange
        temp = df2.loc[(df2['name'] == name), 'weight']
        x = row[3] + temp.iloc[0] #
        df1.set_value(index,'D',x)
    print df1


df1 = pd.DataFrame({'name' : ['alex','bob', 'chris'], 'weight' : [140,150,160], 'A' : ['1','2','3'], 'B' : ['4','5','6']})
df2 = pd.DataFrame({'name' : ['alex','bob', 'chris'], 'weight' : [180,190,200], 'C' : ['1','2','3'], 'D' : ['4','5','6']})
print df1
print df2

foo(df1,df2)