简体   繁体   English

有没有办法循环遍历python中的列表?

[英]Is there a way to loop through a list in python?

I am trying to create a 2X2 table with the left side containing a list of the names of columns (from another dataframe) and the right side containing the sum of the integers in the rows of the corresponding columns.我正在尝试创建一个 2X2 表,左侧包含列名列表(来自另一个数据帧),右侧包含相应列的行中整数的总和。

The result of what I am trying to do would be something like this:我试图做的结果是这样的:

在此处输入图片说明

If you ask me, the coding sequence would look something like this:如果你问我,编码序列看起来像这样:

  • Store content in cell A1 in a string variable x;将单元格 A1 中的内容存储在字符串变量 x 中;
  • Go to dataframe, and find the column with that name;转到数据框,找到具有该名称的列;
  • Sum said column and print the value in B1;对所述列求和并在 B1 中打印值;
  • Go one row down and x takes on the value of A2;向下一行,x 取 A2 的值;
  • Loop 6 times.循环6次。

I tried using this code:我尝试使用此代码:

df.loc['Total',:]= df.sum(axis=0)

With the hope that once I get the total at the bottom, I would be able to create another column, transposed.希望一旦我得到底部的总数,我就可以创建另一列,转置。 But my python terminal hung anytime I ran that code (just 50,000 rows).但是每当我运行该代码(只有 50,000 行)时,我的 python 终端就会挂起。

I also tried this我也试过这个

df['column name'].sum(axis=0)

But that only gave me the sum of one column.但这只给了我一列的总和。 I have about 30 columns.我有大约 30 列。 And furthermore, I can only "Print" the codes.此外,我只能“打印”代码。 It doesn't put them in the table accordingly as would have been useful.它没有将它们相应地放在表格中,因为它们会很有用。 The end goal really is just the table.最终目标真的只是桌子。 Anyway, suggestions or links to where it has been done before would be appreciated.无论如何,我们将不胜感激。 Thanks谢谢

In [3]: df = pd.DataFrame({"a": [1, 3, 5, 7, 9, 0], "b":[5, 8, 1, 0, 3, 5], "c": [6, 2, 9, 9, 4, 2]})                                                   

In [4]: df                                                                      
Out[4]: 
   a  b  c
0  1  5  6
1  3  8  2
2  5  1  9
3  7  0  9
4  9  3  4
5  0  5  2

In [5]: df.sum()                                                                
Out[5]: 
a    25
b    22
c    32
dtype: int64

I'm a bit confused by the wording of your question.我对你问题的措辞有些困惑。 Is this the answer you want?这是你想要的答案吗? Or do you want a method doing the same thing except using loops?或者你想要一个方法做同样的事情,除了使用循环?

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

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