pandas 迭代器中的返回值类型和熊猫中迭代器的列名打印

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

type of return value in itertuples and print column names of itertuples in pandas

python-3.xpandas

提问by user7786493

I have a DataFrame as follows:

我有一个 DataFrame 如下:

          a         b         c         d
0  0.140603  0.622511  0.936006  0.384274
1  0.246792  0.961605  0.866785  0.544677
2  0.710089  0.057486  0.531215  0.243285

I want to iterate the df with itertuples() and print the values and column names of each row. Currently I know the following method:

我想用 itertuples() 迭代 df 并打印每行的值和列名。目前我知道以下方法:

df=pd.DataFrame(np.random.rand(3,4),columns=['a','b','c','d'])
for item in df.itertuples():
    print(item)

And the output is:

输出是:

Pandas(Index=0, a=0.55464273035498401, b=0.50784779485386233, c=0.55866384351761911, d=0.35969591433338755)
Pandas(Index=1, a=0.60682158587529356, b=0.37571390304543184, 
c=0.13566419305411737, d=0.55807909125502775)
Pandas(Index=2, a=0.73260693374584385, b=0.59246381839030349, c=0.92102184020347211, d=0.029942550647279687)

Question:

题:

1) I thought the return data of each iteration is a tuple (as suggested by the function name) when the type(df) returns Pandas()?

1)当type(df)返回Pandas()时,我认为每次迭代的返回数据是一个元组(如函数名称所示)?

2) What is the best way to extract the value of 'a', 'b', 'c', 'd' being the column names as I loop through the items of each row?

2)当我遍历每行的项目时,提取“a”、“b”、“c”、“d”作为列名的值的最佳方法是什么?

回答by ayhan

It's a named tuple.

这是一个命名元组

To access the values of the named tuple, either by label:

要访问命名元组的值,可以通过标签:

for item in df.itertuples():
    print(item.a, item.b)

or by position

或按职位

for item in df.itertuples():
    print(item[1], item[2])