提取熊猫中特定列名的值,如另一列中所列

ire*_*ene 1 python indexing dataframe pandas

标题不太清楚,但这里有一个例子。假设我有:

person  apple  orange  type
Alice   11     23      apple
Bob     14     20      orange
Run Code Online (Sandbox Code Playgroud)

我想得到这个专栏

person new_col
Alice  11
Bob    20
Run Code Online (Sandbox Code Playgroud)

所以我们得到“爱丽丝”行的“苹果”列和“鲍勃”行的“橙色”列。

我在想 iterrows,但这会很慢。有没有更快的方法来做到这一点?

jez*_*ael 6

使用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
Run Code Online (Sandbox Code Playgroud)

如果只需要 2 列 DataFrame 使用assignDataFrame构造函数:

df1 = df[['person']].assign(new_col=df.lookup(df.index, df['type']))
print (df1)
  person  new_col
0  Alice       11
1    Bob       20
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)