【问题标题】:Search for str in a column and create a new list of items在列中搜索 str 并创建新的项目列表
【发布时间】:2019-09-22 23:48:33
【问题描述】:

我有一个数据框火车,其中有一列名为“名称”。我的目标是在名称列中搜索 str“Doc”。我的最终目标是在我的数据框中添加一个名为“Doctor”的新列。列中的值将为 1 或 0。如果列中的名称包含 str“Doc”,则 Doctor 列中的值应为 1。如果不包含“Doc”,则 Doctor 列中的值应该是 0。

这是我到目前为止的代码。我正在尝试创建一个 # 列表,然后我可以将其添加到 Doctor 列中。

temp_list = []
for i in train:
    if i in train[train["Name"].str.contains("Doc")]:
        temp_list.append("1")
    else:
        temp_list.append("0")

运行此函数后,它返回一个 1 的列表,但没有 0 的列表

['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1']

【问题讨论】:

    标签: python python-3.x list function dataframe


    【解决方案1】:

    试试这个:

    temp_list = []
    for word in train["Name"]:
      temp_list.append('1') if 'Doc' in word else temp_list.append('0')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      相关资源
      最近更新 更多