@@ -883,43 +883,66 @@ def iterrows(self):
883
883
884
884
def itertuples (self , index = True , name = "Pandas" ):
885
885
"""
886
- Iterate over DataFrame rows as namedtuples, with index value as first
887
- element of the tuple.
886
+ Iterate over DataFrame rows as namedtuples.
888
887
889
888
Parameters
890
889
----------
891
- index : boolean , default True
890
+ index : bool , default True
892
891
If True, return the index as the first element of the tuple.
893
- name : string , default "Pandas"
892
+ name : str , default "Pandas"
894
893
The name of the returned namedtuples or None to return regular
895
894
tuples.
896
895
896
+ Yields
897
+ -------
898
+ collections.namedtuple
899
+ Yields a namedtuple for each row in the DataFrame with the first
900
+ field possibly being the index and following fields being the
901
+ column values.
902
+
897
903
Notes
898
904
-----
899
905
The column names will be renamed to positional names if they are
900
906
invalid Python identifiers, repeated, or start with an underscore.
901
907
With a large number of columns (>255), regular tuples are returned.
902
908
903
- See also
909
+ See Also
904
910
--------
905
- iterrows : Iterate over DataFrame rows as (index, Series) pairs.
906
- iteritems : Iterate over (column name, Series) pairs.
911
+ DataFrame.iterrows : Iterate over DataFrame rows as (index, Series)
912
+ pairs.
913
+ DataFrame.iteritems : Iterate over (column name, Series) pairs.
907
914
908
915
Examples
909
916
--------
910
-
911
- >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]},
912
- index=['a', 'b'])
917
+ >>> df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
918
+ ... index=['dog', 'hawk'])
913
919
>>> df
914
- col1 col2
915
- a 1 0.1
916
- b 2 0. 2
920
+ num_legs num_wings
921
+ dog 4 0
922
+ hawk 2 2
917
923
>>> for row in df.itertuples():
918
924
... print(row)
919
925
...
920
- Pandas(Index='a', col1=1, col2=0.10000000000000001)
921
- Pandas(Index='b', col1=2, col2=0.20000000000000001)
926
+ Pandas(Index='dog', num_legs=4, num_wings=0)
927
+ Pandas(Index='hawk', num_legs=2, num_wings=2)
928
+
929
+ By setting the `index` parameter to False we can remove the index
930
+ as the first element of the tuple:
931
+
932
+ >>> for row in df.itertuples(index=False):
933
+ ... print(row)
934
+ ...
935
+ Pandas(num_legs=4, num_wings=0)
936
+ Pandas(num_legs=2, num_wings=2)
937
+
938
+ With the `name` parameter set we set a custom name for the yielded
939
+ namedtuples:
922
940
941
+ >>> for row in df.itertuples(name='Animal'):
942
+ ... print(row)
943
+ ...
944
+ Animal(Index='dog', num_legs=4, num_wings=0)
945
+ Animal(Index='hawk', num_legs=2, num_wings=2)
923
946
"""
924
947
arrays = []
925
948
fields = []
0 commit comments