【问题标题】:Creating dataframe similar to the index and match functions in excel在excel中创建类似于索引和匹配函数的数据框
【发布时间】:2016-05-04 14:26:38
【问题描述】:

我正在尝试完成的简短示例: df1 与 col1 = 'All_stocks' 和 col2 = 'earnings' df2 与 col1 = 'Stock_tix' 根据我在 df2 col1 中的“股票行情”,我希望 df2 中的 col 2 等于 df1 的收益

df1 =

All_stocks    Earnings   
AAPL          50
TSLA          43
RNR           39
FB            90

df2 =

Stock_tix
AAPL
TSLA

所以我试图根据上面的内容找出使 df2 看起来如下所示的代码:

df2 =

Stock_tix    Earnings
AAPL         50
TSLA         43

我已经尝试遍历数据框、.loc .ix 等,但似乎没有什么能像 Excel 中的简单匹配和索引那样工作。我对 python 非常了解,这是我在 Stackoverflow 上的第一篇文章,所以如果有人能指出我正确的方向,我将不胜感激!谢谢!

【问题讨论】:

  • 欢迎来到 Stackoverflow。您的问题很好,但更好的是添加您的代码。如果不工作,没问题。您可以查看Minimal, Complete, and Verifiable example
  • 嘿,谢谢!我今晚去看看

标签: python-2.7 pandas dataframe


【解决方案1】:

我认为您可以使用mergedrop 删除列All_stocks

print pd.merge(df2,df1, left_on='Stock_tix', right_on='All_stocks').drop('All_stocks',axis=1)
  Stock_tix  Earnings
0      AAPL        50
1      TSLA        43

【讨论】:

  • 它需要一点点调整,但合并功能正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 2014-12-10
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 2022-11-25
相关资源
最近更新 更多