【问题标题】:How to select all observations whose name starts with a specific element in python如何选择名称以python中特定元素开头的所有观察值
【发布时间】:2022-07-21 21:45:00
【问题描述】:

我有一个数据框,我想在其中创建一个虚拟变量,当资产类以 D 开头时取值为 1。我想要所有以 D 开头的变体。你会怎么做?

数据看起来像

dic = {'Asset Class':  ['D.1', 'D.12', 'D.34', 'F.3', 'G.12', 'D.2']}
df = pd.DataFrame(dic)

我想要的是

dic_want = {'Asset Class':  ['D.1', 'D.12', 'D.34', 'F.3', 'G.12', 'D.2'],
            'Asset Dummy':  [1,1,1,0,0,1]}
df_want = pd.DataFrame(dic_want)

我试过了

df_want["Asset Dummy"] = ((df["Asset Class"] == df.filter(like="D"))).astype(int)

我收到以下错误消息:ValueError: Columns must be the same length as key

我也试过

CSDB["test"] = ((CSDB["PAC2"] == CSDB.str.startswith('D'))).astype(int)

我在哪里收到错误消息 AttributeError: 'DataFrame' object has no attribute 'str'。 我尝试使用标准方法(as.typ(str) 和 to_string())将我的对象转换为字符串,但它也不起作用。这可能是另一个问题,但我发现只有一个帖子具有相同的问题,但该帖子没有令人满意的答案。

有什么想法可以解决我的问题吗?

【问题讨论】:

    标签: python string object startswith


    【解决方案1】:

    您可以在df['Asset Class'] 上使用Series.str.startswith

    >>> df['Asset Dummy'] = df['Asset Class'].str.startswith('D').astype(int)
    >>> df
      Asset Class  Asset Dummy
    0         D.1            1
    1        D.12            1
    2        D.34            1
    3         F.3            0
    4        G.12            0
    5         D.2            1
    

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 2011-07-04
      • 2020-02-20
      • 2017-06-19
      相关资源
      最近更新 更多