简体   繁体   English

Pandas数据帧:组合位置和整数索引

[英]Pandas dataframes: Combining location and integer indexing

I'd like to change a value in a dataframe by addressing the rows by using integer indexing (using iloc) , and addressing the columns using location indexing (using loc). 我想通过使用整数索引(使用iloc)来寻址行,并使用位置索引(使用loc)来寻址列来更改数据帧中的值。

Is there anyway to combine these two methods? 无论如何要结合这两种方法吗? I believe it would be the same as saying, I want the 320th row of this dataframe and the column that has the title "columnTitle". 我相信它会像说的那样,我想要这个数据帧的第320行和标题为“columnTitle”的列。 Is this possible? 这可能吗?

IIUC you can call iloc directly on the column: 您可以直接在列上调用iloc

In [193]:
df = pd.DataFrame(columns=list('abc'), data = np.random.randn(5,3))
df

Out[193]:
          a         b         c
0 -0.810747  0.898848 -0.374113
1  0.550121  0.934072 -1.117936
2 -2.113217  0.131204 -0.048545
3  1.674282 -0.611887  0.696550
4 -0.076561  0.331289 -0.238261

In [194]:
df['b'].iloc[3] = 0
df

Out[194]:
          a         b         c
0 -0.810747  0.898848 -0.374113
1  0.550121  0.934072 -1.117936
2 -2.113217  0.131204 -0.048545
3  1.674282  0.000000  0.696550
4 -0.076561  0.331289 -0.238261

Mixed integer and label based access is supported by ix . ix支持混合整数和基于标签的访问。

df = pd.DataFrame(np.random.randn(5,3), columns=list('ABC'))
>>> df
          A         B         C
0 -0.473002  0.400249  0.332440
1 -1.291438  0.042443  0.001893
2  0.294902  0.927790  0.999090
3  1.415020  0.428405 -0.291283
4 -0.195136 -0.400629  0.079696

>>> df.ix[[0, 3, 4], ['B', 'C']]
          B         C
0  0.400249  0.332440
3  0.428405 -0.291283
4 -0.400629  0.079696

df.ix[[0, 3, 4], ['B', 'C']] = 0

>>> df
          A         B         C
0 -0.473002  0.000000  0.000000
1 -1.291438  0.042443  0.001893
2  0.294902  0.927790  0.999090
3  1.415020  0.000000  0.000000
4 -0.195136  0.000000  0.000000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM