【问题标题】:How do I overwrite the value of a specific index/column in a DataFrame?如何覆盖 DataFrame 中特定索引/列的值?
【发布时间】:2017-03-30 14:59:42
【问题描述】:

我有一个数据框Exposure,其零构造如下:

Exposure = pd.DataFrame(0, index=dates, columns=tickers)

还有一个带有数据的 DataFrame df

我想将df的部分数据填充到Exposure

    for index, column in df.iterrows():
        # value of df(index,column) to be filled at Exposure(index,column)

如何用df(index,column) 的值覆盖Exposure(index,column) 的值?

【问题讨论】:

    标签: python python-3.x dataframe


    【解决方案1】:

    最好的办法是:

    df.loc[index, column] = value
    

    【讨论】:

    • 根据 pandas 本身,这是首选方法,因为 dataframe[rows, columns] 不是类型安全的
    【解决方案2】:

    你可以试试这个:

    for index, column in df.iterrows():
        Exposure.loc[index, column.index] = column.values
    

    这将在暴露中创建新的索引和列,如果它们不存在,如果你想避免这种情况,首先构造公共索引和列,然后以向量化的方式进行分配(避免 for 循环):

    common_index = Exposure.index.intersection(df.index)
    common_columns = Exposure.columns.intersection(df.columns)
    Exposure.loc[common_index, common_columns] = df.loc[common_index, common_columns]
    

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 1970-01-01
      • 2023-01-03
      • 2019-12-28
      • 2020-08-07
      • 2011-05-24
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      相关资源
      最近更新 更多