J.J.
J.J.

Reputation: 73

Reference previous column

I am looping through every other column of a dataframe comparing that value to the previous columns in a new column but I can't seem to reference correctly the previous column. I tried using shift but it doesn't seem to work on columns.

df = pd.DataFrame(np.random.randn(8, 4),columns=['A', 'B', 'C', 'D'])
for x in df.ix[:, 1::2]:

    df['Diff']=df[x]<df.index[x-1]

print (df)

Upvotes: 0

Views: 93

Answers (2)

Yuca
Yuca

Reputation: 6091

Keeping it as close to your logic as possible:

df = pd.DataFrame(np.random.randn(8, 4),columns=['A', 'B', 'C', 'D'])
for x in df.columns[1::2]:    
    print(df.iloc[:,df.columns.get_loc(x)] < df.iloc[:,df.columns.get_loc(x)-1])

Upvotes: 1

addicted
addicted

Reputation: 3051

Maybe this?

for i in range(1, df.shape[1]):
    df['diff'] = df[df.columns[i]] < df[df.columns[i-1]]

Upvotes: 1

Related Questions