magicsword
magicsword

Reputation: 1289

pandas dataframe .loc row values

I have a dataframe that contains 3 columns and I'm using one of the columns as an index to find the corresponding values in the others. As shown.

loop
data = []
a,b,c = df.loc[df['W'].index][['W','X','Y']]
data.append({'W':a, 'X':b, 'Y':c,})
end loop

output:

[{'W':'a', 'X':'b', 'Y':'c'}]

The problem is that instead of giving me the values in the rows it gives me the names of the columns 'W,X,Y'. I need to get the values in columns W,X and Y.

Upvotes: 1

Views: 719

Answers (1)

jezrael
jezrael

Reputation: 862571

If need add values to dict, use:

data.append({'W':df.W.tolist(), 'X':df.X.tolist(), 'Y':df.Y.tolist()})

But same output is if use:

data.append(df[['W','X','Y']].to_dict(orient='list'))

Sample:

np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(5,3)), columns=list('WXY'), index=[2,3,4,5,6])
print (df)
   W  X  Y
2  8  8  3
3  7  7  0
4  4  2  5
5  2  2  2
6  1  0  8

data = []
data.append({'W':df.W.tolist(), 'X':df.X.tolist(), 'Y':df.Y.tolist()})
print (data)
[{'X': [8, 7, 2, 2, 0], 'W': [8, 7, 4, 2, 1], 'Y': [3, 0, 5, 2, 8]}]

data = []
data.append(df[['W','X','Y']].to_dict(orient='list'))
print (data)
[{'X': [8, 7, 2, 2, 0], 'W': [8, 7, 4, 2, 1], 'Y': [3, 0, 5, 2, 8]}]

Upvotes: 1

Related Questions