【问题标题】:Pandas, why can't I assign with df.loc[condition, 'col'] = df.loc[condition, 'col'].modification?熊猫,为什么我不能用 df.loc[condition, 'col'] = df.loc[condition, 'col'].modification 赋值?
【发布时间】:2022-07-05 17:09:40
【问题描述】:

我正在尝试使用

更改数据框列
df.loc[df['xxx'].notna(), 'xxx'] = df.loc[df['xxx'].notna(), 'xxx'].astype(str).str[:10].str.replace('-','')

这似乎对列的值没有任何影响。 在没有 loc[conditional, 'xxx'] 的情况下运行它时,它似乎确实有效

df['xxx'] = df['xxx'].astype(str).str[:10].str.replace('-','')

这挑战了我对 pandas 的核心理解,因为我总是使用 .loc 来更改行的子集。

我使用的是熊猫 1.2.4

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我的测试是效果,测试代码如下。 但是我的版本是1.0.4。

    import pandas as pd
    print(pd.__version__)
    df = pd.DataFrame(
        {'xxx': ['AABBCC-DDEEE', 'DIs-sssssssssssP', 'KKK', 'A', 'A'],
         'tmp': [1, 2, 3, 4, 5]})
    print(df)
    df.loc[df['xxx'].notna(), 'xxx'] = df.loc[df['xxx'].notna(), 'xxx'].astype(str).str[:10].str.replace('-','')
    print(df)
    

    结果如下

    1.0.4
                    xxx  tmp
    0      AABBCC-DDEEE    1
    1  DIs-sssssssssssP    2
    2               KKK    3
    3                 A    4
    4                 A    5
             xxx  tmp
    0  AABBCCDDE    1
    1  DIsssssss    2
    2        KKK    3
    3          A    4
    4          A    5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-14
      • 2021-08-22
      • 1970-01-01
      • 2013-11-18
      • 2011-11-20
      • 2020-06-20
      • 2021-09-27
      • 1970-01-01
      相关资源
      最近更新 更多