【问题标题】:How to move text from old column to newly created columns pandas如何将文本从旧列移动到新创建的列 pandas
【发布时间】:2022-10-14 21:34:56
【问题描述】:

我有以下代码,仅适用于名为“Desc”的一列。如何更改代码以将其应用于两列? “Desc”和“Desc1”?

df = pd.DataFrame({'Desc':['cat is black','dog is white']})
kw = ['cat','dog']
for k in kw:
   df[k + ' col'] = df.Desc.map(lambda s: s if k in s else '' )

[只有一列'Desc'的输出是:]

但现在我想用这个函数来选择两列 Desc 和 Desc 1

【问题讨论】:

  • 您好,我已经加载了图像以查看所需的输出
  • 也许您应该使用apply(function)function 中获取整行并检查每一行中的两列。
  • 您应该显示两列的数据和两列的预期结果。如果一列有cat is whilte 而另一列有cat is black 在同一行怎么办?
  • 我不知道你在新列中想要什么,但你总是可以做df.Desc.map(...) + df.Desc1.map(...),它会连接字符串。

标签: python pandas


【解决方案1】:

您没有显示您期望的结果,但您始终可以使用

df[k + ' col'] = df.Desc.map(...) + "," + df.Desc1.map(...)

但这会在空单元格中添加,,并且会重复重复值。

import pandas as pd

df = pd.DataFrame({
    'Desc':  ['cat is black', 'dog is white'],
    'Desc1': ['cat is white', 'dog is white'],
})

kw = ['cat','dog']
for k in kw:
   df[k + ' col'] = df.Desc.map(lambda s: s if k in s else '') + ',' + df.Desc1.map(lambda s: s if k in s else '')
   
print(df.to_string())

结果:

           Desc         Desc1                    cat col                    dog col
0  cat is black  cat is white  cat is black,cat is white                          ,
1  dog is white  dog is white                          ,  dog is white,dog is white

但是您也可以使用.apply(function, args=[...], axis=1) 将整行发送到函数并在函数中运行更复杂的代码

import pandas as pd

df = pd.DataFrame({
    'Desc':  ['cat is black', 'dog is white'],
    'Desc1': ['cat is white', 'dog is white'],
})

def select(row, word):
    result = []

    if word in row['Desc']:
        result.append(row['Desc'])

    if word in row['Desc1']:
        result.append(row['Desc1'])
        
    # skip duplicated
    if len(result) > 1 and result[0] == result[1]:
        result = result[:1]
        
    return ",".join(result)
    
kw = ['cat','dog']
for word in kw:
   df[f'{word} col'] = df.apply(select, args=[word], axis=1)
   
print(df.to_string())

结果:

           Desc         Desc1                    cat col       dog col
0  cat is black  cat is white  cat is black,cat is white              
1  dog is white  dog is white                             dog is white

【讨论】:

  • 首先感谢您的帮助。你的回答真的很有用,是我需要的输出。但现在我面临另一个问题。我在上面发表了我的问题。你能检查一下吗?
【解决方案2】:
    def select(row, word):
    result = []
    if word in row ['Color']:
        result.append(row['Color'])
        
    if word in row ['Clorof']:
        result.append(row['Clorof'])    
   
    if word in row ['Diat']:
        result.append(row['Diat'])  
        
    if word in row ['Scene']:
        result.append(row['Scene'])
        
    if word in row ['Ciano']:
        result.append(row['Ciano'])
        
    if word in row ['Ameb_Cist']:
        result.append(row['Ameb_Cist'])
        
    if word in row ['Vortic']:
        result.append(row['Vortic'])
                          
    if word in row ['CiliadG']:
        result.append(row['CiliadG']) 
        
    if word in row ['Bact_fung']:
        result.append(row['Bact_fung'])  
        
    if word in row ['Bact_fil']:
        result.append(row['Bact_fil'])  
        
    if word in row ['Agl_EPS']:
        result.append(row['Agl_EPS']) 
        
    if word in row ['Microfla_ciliad']:
        result.append(row['Microfla_ciliad']) 
        
    if word in row ['Cristais']:
        result.append(row['Cristais']) 
        
    if len(result) > 1 and result[0] == result[1]:
        result = result[:1]
        
    return ",".join(result)

kw= ['descolor', 'clorofitas','Diatom', 'Scene', 'Cianobact', 'Cistos', 'Vorticelas', 'Ciliados', 'fungos', 'filam', 'Aglom','Microflag', 'Cristais']
for word in kw:
    df[f'{word} col'] = df.apply(select, args=[word], axis=1)
 
print(df.to_string())

你的回答真的很有用,是我需要的输出。所以我申请了我的数据,最后它给了我一个错误“TypeError:'float'类型的参数不可迭代”。你知道这有多正确吗?

【讨论】:

    【解决方案3】:
    import pandas as pd
    
    
    df = pd.DataFrame({'Desc':['cat is black','dog is white']})
    kw = ['cat','dog']
    
    i = 0 #iterator
    for k in kw:
        #Creates an empty column
        df[k + 'col'] = "" 
        #Assigns the value in the cell based on its location in df["Desc"]
        df[k + 'col'][i] = df["Desc"][i]
        i = i+1 #iterates
    

    【讨论】:

    • 您的代码中没有 Desc1 列 - 所以它不能解决问题。
    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2020-08-21
    • 2021-09-11
    相关资源
    最近更新 更多