【问题标题】:How to add an empty column to a dataframe? - followup [duplicate]如何将空列添加到数据框中? - 跟进[重复]
【发布时间】:2020-11-18 12:47:05
【问题描述】:

此问题已回答here。然而,有以下输入:

print(type(df1))
df1['x'] = np.nan

我得到以下输出:

<class 'pandas.core.frame.DataFrame'>
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:2: SettingWithCopyWarning:


A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

我的案例与所附链接中的案例有何不同?

【问题讨论】:

    标签: python-3.x pandas dataframe jupyter


    【解决方案1】:

    当您创建df1 时,此警告的真正原因可能是几行代码。如果你有这样的事情:

    df1 = another_df[['col1', 'col2']]
    

    有时您会获得原始数据框的一部分,有时您会获得副本。很难说你得到了什么。我相信这与原始框架中的值与引用语义有关。

    要消除警告,请进行显式复制:

    df1 = another_df[['col1', 'col2']].copy()
    df1['new_col'] = np.na
    

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 2021-06-26
      • 1970-01-01
      • 2017-07-25
      • 2018-12-14
      • 1970-01-01
      • 2018-10-14
      • 2018-10-26
      • 1970-01-01
      相关资源
      最近更新 更多