【问题标题】:Pandas - Using value from a column as an index to extract value from an existing column into a new columnPandas - 使用列中的值作为索引将现有列中的值提取到新列中
【发布时间】:2022-01-23 01:29:04
【问题描述】:

Datframe 如下所示。我想添加另一列“newcol”,它使用“价格”列中的值来查找“名称”列中的位置。

     name  price stock
1  orange     2   Yes
2  banana     3    No
3  lemon      7   Yes
4  mango     21    No
5  apple     11   Yes

输出

     name  price stock newcol
1  orange     2   Yes  banana
2  banana     3    No  lemon
3  lemon      7   Yes
4  mango     21    No
5  apple     11   Yes

M码明显错误

import pandas as pd
df = pd.DataFrame({
    'name':
    ['orange','banana','lemon','mango','apple'],
    'price':
    [2,3,7,21,11],
    'stock':
    ['Yes','No','Yes','No','Yes']
})


print(df)

df['newcol'] = df['name'].iloc[df['price'].iloc[df['price'].index]]

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    试试这个:

    df['newcol'] = df.loc[df['price'], 'name'].reset_index(drop=True)
    

    【讨论】:

    • 我收到以下错误“不再支持将列表喜欢传递给 .loc 或 [] 且缺少任何标签...”
    • 您的价格列是否包含您的索引不包含的数字?
    • df.index.isin(df.price).any() 应该告诉你。
    猜你喜欢
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多