像 Python 字典一样迭代 Pandas 数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33204279/
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-09-14 00:04:15  来源:igfitidea点击:

Iterate Pandas dataframe like a python dictionary

pythonpandas

提问by jwillis0720

I have a unique index for each row, so my dataframe looks like this -

我的每一行都有一个唯一的索引,所以我的数据框看起来像这样 -

>>>df.head()
    Alignment   Sequence    Sequence2b  Post2b  SequenceLength  Sequence2bLength    Name    Year    Clade   Country Patient medoid
index                                               
44644   MRV-KET----QMNWP---N----------L---W---K-------...   MRVKETQMNWPNLWKWGTLIFGLVIICSAADNLWVTVYYGVPVWRD...       AGY 778 0   AA111a_WG3  2009    01_AE   TH  AA111   NA
3616    ------T----QMNWQ---H----------L---W---K-------...   TQMNWQHLWKWGTLILGLVIICSASNLWVTVYYGVPVWKDADTTLF...   AVVKINENATLDDTSY    LKN 822 16  041_WK32    -   B   CH  041 NA
36025   MRV-KET----QMSWP---N----------L---W---K-------...   MRVKETQMSWPNLWKWGTLILGLVIMCSASDNLWVTVYYGVPVWRD...   D   NTS 843 1   AE_Env_CR11_Jan09D  2009    01_AE   TH  CR11    NA
42027   MRV-KGI----RKNCQ---H----------L---W---R-------...   MRVKGIRKNCQHLWRWGIMLLGMLMICSTAEKLWVTVYYGVPVWRE...   DADEIHNDDNSS    SCY 862 12  CR0058S 2002    B   US  -   NA
31626   MRV-RGI----PRNYP---Q----------W---W---I-------...   MRVRGIPRNYPQWWIWGILGFWMIIICRVMESSWVTVYYGVPVWTD...   DAIPLNGNSSNSSSNSSEY LIN 852 19  03ZASK006B2 2003    C   ZA  SK006   NA

Is there a way to iterate it easily sort of like a key,value pair like a dictionary like this?

有没有办法像这样的字典一样轻松地迭代它,就像键值对一样?

for index in df:
   print index, df[index]['Name']
   break
 >>>44644 : {Name:AA11a_WG3}

Here is what I have come up with, but I'm not sure if this is the most "pythonic" way.

这是我想出的,但我不确定这是否是最“pythonic”的方式。

 for index in df.index:
     print index, df[df.index == index].Name

The df.to_dict does not work since it removes the index.

df.to_dict 不起作用,因为它删除了索引。

回答by Alexander

You probably want to use iterrows().

您可能想要使用iterrows().

for idx, row in df.iterrows():
     print((idx, row.Name))