【问题标题】:Looking up data from a row in a single dataframe to create a new column in the same dataframe从单个数据框中的行中查找数据以在同一数据框中创建新列
【发布时间】:2020-02-26 22:01:19
【问题描述】:

我是 Python 和 Pandas 的新手,并且一直在寻找一种优雅的解决方案来向 Pandas 数据框添加列。我需要在一行中查找“名称”和“日期”组合的“”,其中“分母'将匹配'分子'。它被用于为大约有 10,000 个条目的大型股票投资组合创建比率。在下面的示例中,新列的第一个值将包含 0.00,第二个值将包含 345.943,依此类推。我已经尝试了许多我在 stackoverflow 上找到的方法,但没有一种方法能以我正在寻找的方式工作。任何帮助将不胜感激。

Sample Dataframe is here

这里是示例数据:

分子 名称 日期值 分母 ------------------ ------ --------- ----- -- ------------- 60 收入 NTNX - Nutanix Inc 2016-01-01 102.697 总资产 61 收入 NTNX - Nutanix Inc 2016-04-01 114.690 总资产 62 收入 NTNX - Nutanix Inc 2016-07-01 198.267 总资产 63 收入 NTNX - Nutanix Inc 2016-10-01 188.561 总资产 285 总资产 NTNX - Nutanix Inc 2016-01-0 **0.000** 1 286 总资产 NTNX - Nutanix Inc 2016-04-01 **345.943* 1 287 总资产 NTNX - Nutanix Inc 2016-07-01 399.08 1 288 总资产 NTNX - Nutanix Inc 2016-10-01 648.263 1

【问题讨论】:

  • 您好,欢迎来到 SO,阅读 minimal reproducible example 并使用您的示例数据(作为文本)和示例输出重新格式化您的问题。
  • 谢谢。感谢您的帮助,当您走出起跑门时,这始终是一次很好的学习体验。

标签: python pandas


【解决方案1】:

我没有看到任何简单的方法来做到这一点。我发现的唯一方法是:

# Get two copy of dataframe, might have to call .copy here
df_numerator, df_denominator = dataframe, dataframe

df_numerator["key"] = df_numerator["numerator"]
df_denominator["key"] = df_denominator["denominator"]

# This will match the row with same Name, Date and key tuples.
merged_df = df_numerator.join(df_denominator, on=["Name", "Date", "key"]
# Will work provided the length matches
dataframe["new_column"] = merged_df["value"]

【讨论】:

  • 谢谢卡尔!我会试一试,让你知道结果。我还没有使用.copy。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
  • 2012-11-14
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
  • 2016-03-11
  • 1970-01-01
相关资源
最近更新 更多