Python 按索引遍历数据帧

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36864690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:27:45  来源:igfitidea点击:

Iterate through a dataframe by index

pythonpython-3.xpandas

提问by Stacey

I have a dataframe called staticData which looks like this:

我有一个名为 staticData 的数据框,它看起来像这样:

                         narrow_sector       broad_sector country exchange  \
unique_id                                                                    
BBG.MTAA.STM.S          Semiconductors         Technology      CH     MTAA   
BBG.MTAA.CNHI.S  Machinery-Diversified         Industrial      GB     MTAA   
BBG.MTAA.FCA.S      Auto Manufacturers  Consumer Cyclical      GB     MTAA   
BBG.MTAA.A2A.S                Electric          Utilities      IT     MTAA   
BBG.MTAA.ACE.S                Electric          Utilities      IT     MTAA 

I am trting to iterate through the dataframe row by row picking out two bits of information the index (unique_id) and the exchange. I am having a problem iterating on the index. Please see my code:

我正在逐行遍历数据帧,从中挑选出两位信息,即索引 (unique_id) 和交换。我在迭代索引时遇到问题。请看我的代码:

 for i, row in staticData.iterrows():

        unique_id = staticData.ix[i]

        exchange = row['exchange']

I have tried unique_id = row['unique_id'], but can't get it to work...

我试过 unique_id = row['unique_id'],但无法让它工作......

I am trying to return say for row1

我正在尝试为 row1 返回 say

unique_id = BBG.MTAA.STM.S
exchange = MTAA 

采纳答案by EdChum

You want the following:

您需要以下内容:

for i, row in staticData.iterrows():
    unique_id = i
    exchange = row['exchange']

i will be the index label value

我将是索引标签值

Example:

例子:

In [57]:
df = pd.DataFrame(np.random.randn(5,3), index=list('abcde'), columns=list('fgh'))
df

Out[57]:
          f         g         h
a -0.900835 -0.913989 -0.624536
b -0.854091  0.286364 -0.869539
c  1.090133 -0.771667  1.258372
d -0.721753 -0.329211  0.479295
e  0.520786  0.273722  0.824172

In [62]:
for i, row in df.iterrows():
    print('index: ', i, 'col g:', row['g'])

index:  a col g: -0.913988608754
index:  b col g: 0.286363847188
index:  c col g: -0.771666520074
index:  d col g: -0.329211394286
index:  e col g: 0.273721527592

回答by knagaev

May be more pandasian way?

可能是更熊猫的方式?

staticData.apply((lambda x: (x.name, x['exchange'])), axis=1)