user189035
user189035

Reputation: 5789

How to use the values of one column to access values in another column?

How to use the values of one column to access values in another

import numpy
impot pandas

numpy.random.seed(123)
df = pandas.DataFrame((numpy.random.normal(0, 1, 10)), columns=[['Value']])
df['bleh'] = df.index.to_series().apply(lambda x: numpy.random.randint(0, x + 1, 1)[0])

so how to access the value 'bleh' for each row?

df.Value.iloc[df['bleh']]

Edit:

Thanks to @ScottBoston. My DF constructor had one layer of [] too much. The correct answer is:

numpy.random.seed(123)
df = pandas.DataFrame((numpy.random.normal(0, 1, 10)), columns=['Value'])
df['bleh'] = df.index.to_series().apply(lambda x: numpy.random.randint(0, x + 1, 1)[0])
df['idx_int'] = range(df.shape[0])
df['haa']     = df['idx_int']  - df.bleh.values
df['newcol']  = df.Value.iloc[df['haa'].values].values 

Upvotes: 1

Views: 98

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Try:

df['Value'].tolist()

Output:

[-1.0856306033005612,
 0.9973454465835858,
 0.28297849805199204,
 -1.506294713918092,
 -0.5786002519685364,
 1.651436537097151,
 -2.426679243393074,
 -0.42891262885617726,
 1.265936258705534,
 -0.8667404022651017]

Your dataframe constructor still needs to be fixed.


Are you looking for:

df.set_index('bleh')

output:

         Value
bleh          
0    -1.085631
1     0.997345
2     0.282978
1    -1.506295
4    -0.578600
0     1.651437
0    -2.426679
4    -0.428913
1     1.265936
7    -0.866740

If so you, your dataframe constructor has as extra set of [] in it.

np.random.seed(123)
df = pd.DataFrame((np.random.normal(0, 1, 10)), columns=['Value'])
df['bleh'] = df.index.to_series().apply(lambda x: np.random.randint(0, x + 1, 1)[0])

columns paramater in dataframe takes a list not a list of list.

Upvotes: 1

Related Questions