简体   繁体   English

遍历熊猫数据帧连续的列

[英]iterate through pandas dataframe consecutive columns

I am trying to create a loop in pandas to calculate difference between consecutive columns and give output in a new column: 我试图在熊猫中创建一个循环,以计算连续列之间的差异,并在新列中提供输出:

Original df: 原始df:

**201601** **201602** **201603**  
100           200         500

Desired output 所需的输出

**201601** **201602** **201603**  **201602_201601** **201603_02**
100           200         500         100          300

My code is which I had modified from a stackoverflow post ([ add columns to a data frame calculated by for loops in python ): 我的代码是我从stackoverflow帖子修改的([ 将列添加到由python中的for循环计算的数据帧中 ):

for i in df.iloc[:,2:5]:
  for j in df.iloc[:,2:5]:
    if i == j:
        break
    else:
        bina = df[i]-df[j]
        df['MOM_' + str(j) + '_' + str(i)] = bina
df.head()

However, the output I get is as below: 但是,我得到的输出如下:

**201601** **201602** **201603**  **201602_201601** **201603_201601** **201603_201602**
100           200         500         100          400   300

I have used pd.diff to do what I needed but couldn't figure out the for loop code. 我已经使用pd.diff来完成我需要的操作,但无法找出for循环代码。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks 谢谢

Using diff and simple list comprehension with zip to construct the columns' names. 使用diff和带有zip简单列表理解来构造列的名称。

cols = [f'{b}_{a}' for (a,b) in zip(df.columns, df.columns[1:])]
df[cols] = df.diff(axis=1).dropna(axis=1)

    201601  201602  201603  201602_201601   201603_201602
0   100     200     500     100             300

Avoid to use for loops at all times when using pandas 避免在使用熊猫时始终使用for循环

This is just fix your code 这只是修复您的代码

col=df.columns
for x,i in enumerate(col):
    for y,j in enumerate(col):
        if  y-x==1 and i!=j:
            bina = df[i]-df[j]
            df['MOM_' + str(j) + '_' + str(i)] = bina
df.columns
Out[1210]: 
Index(['**201601**', '**201602**', '**201603**', 'MOM_**201602**_**201601**',
       'MOM_**201603**_**201602**'],
      dtype='object')

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

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