简体   繁体   English

如何在 pandas dataframe 列中迭代

[英]how to iterate in pandas dataframe columns

i need do some operations with my dataframe我需要用我的 dataframe 做一些操作

my dataframe is我的 dataframe 是

df = pd.DataFrame(data={'col1':[1,2],'col2':[3,4]})

    col1    col2
0      1       3
1      2       4

my operatin is column dependent我的操作依赖于列

for example, i need to add ( + ) .max() of column to each value in this column例如,我需要将 ( + ) .max()列添加到该列中的每个值

so df.col1.max() is 2 and df.col2.max() is 4所以df.col1.max()2df.col2.max()是 4

so my output should be:所以我的 output 应该是:

    col1    col2
0      3       7
1      4       8

i have been try this:我一直在尝试这个:

for i in df.columns:
    df.i += df.i.max()

but

AttributeError: 'DataFrame' object has no attribute 'i'

you can chain df.add and df.max and specify the axis which avoids any loops.您可以链接df.adddf.max并指定避免任何循环的轴。

df1 = df.add(df.max(axis=0))

print(df1)

  col1  col2
0     3     7
1     4     8

To loop through the columns and add the maximum of each column you can do the following:要遍历列并添加每列的最大值,您可以执行以下操作:

for col in df:
    df[col] += df[col].max()

This gives这给

   col1  col2
0     3     7
1     4     8

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

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