问题
The title wasn't too clear but here's an example. Suppose I have:
person apple orange type
Alice 11 23 apple
Bob 14 20 orange
and I want to get this column
person new_col
Alice 11
Bob 20
so we get the column 'apple' for row 'Alice' and 'orange' for row 'Bob'.
I'm thinking iterrows, but that would be slow. Are there faster ways to do this?
回答1:
Use DataFrame.lookup:
df['new_col'] = df.lookup(df.index, df['type'])
print (df)
person apple orange type new_col
0 Alice 11 23 apple 11
1 Bob 14 20 orange 20
If want only 2 column DataFrame use assign or DataFrame
contructor:
df1 = df[['person']].assign(new_col=df.lookup(df.index, df['type']))
print (df1)
person new_col
0 Alice 11
1 Bob 20
df1 = pd.DataFrame({
'person':df['person'].values,
'new_col':df.lookup(df.index, df['type'])},
columns=['person','new_col'])
print (df1)
person new_col
0 Alice 11
1 Bob 20
来源:https://stackoverflow.com/questions/50315700/extract-value-of-a-particular-column-name-in-pandas-as-listed-in-another-column