【问题标题】:How to insert data into a existing dataframe, replacing values according to a conditional如何将数据插入现有数据框中,根据条件替换值
【发布时间】:2020-10-06 11:27:42
【问题描述】:

我希望将信息插入现有数据框,此数据框形状为 2001 行 × 13 列,但是,只有第一列有信息。

我还有 12 列,但这些列与主数据框的维度不同,因此我想使用条件将这些附加列插入主列。 示例数据框:

在一个示例中,我想将 var 列插入到 2001 × 13 数据框中,使用日期作为条件,如果没有日期,它会跳过该行或简单地添加一个 0。
总的来说,我对 python 和编程真的很陌生。

【问题讨论】:

标签: python python-3.x pandas dataframe conditional-statements


【解决方案1】:

如果没有最小的工作示例,很难为您提供明确的建议,但我认为您正在寻找的是 .loc 一个 pd.DataFrame。我建议您执行以下操作:

  • 如果首先将日期转换为日期时间,则使用.loc 选择行在您的情况下效果更好,因此第一步是将此转换为:
# Pandas is quite smart about guessing date format. If this fails, please check the
# documentation https://docs.python.org/3/library/datetime.html to learn more about
# format strings.
df['date'] = pd.to_datetime(df['date'])

# Make this the index of your data frame.
df.set_index('date', inplace=True)
  • 尚不清楚您打算如何使用条件/其他列的内容是什么。使用 .loc 这非常简单
# At Feb 1, 2020, add a value to columns 'var'.
df.loc['2020-02-01', 'var'] = 0.727868
  • 这也可以用于范围:
# Assuming you have a second `df2` which as a datetime columns 'date' with the
# data you wish to add to `df`. This will only work if all df2['date'] are found
# in df.index. You can workout the logic for your case.
df.loc[df2['date'], 'var2'] = df2['vals']

如果逻辑过于复杂且数据框不太大,使用.iterrows 进行迭代可能会更容易,特别是如果您从 Python 开始。

for idx, row in df.iterrows():
    if idx in list_of_other_dates:
        df.loc[i, 'var'] = (some code here)

请澄清一下你的问题,你会得到更好的答案。不要忘记查看documentation

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多