【问题标题】:Type error with strings converted as Series将字符串转换为系列的类型错误
【发布时间】:2021-06-21 05:14:30
【问题描述】:

我想在excel 数据帧中创建一个新列"HQ_LOC",它将来自wharton['conm'] 的字符串j 作为值

xls = excel[(excel['prowess_compustat_h1b'] == 1) | (excel['compustat_h1b'] == 1)]

excel['HQ_LOC'] = pd.Series([])
for name in xls["coname"]:
    for j in wharton['conm']:
        if name == j:
            j
            excel['HQ_LOC'].append(j)

但是当我运行上面的代码时,会出现以下错误,即使我将excel['HQ_LOC'] 转换为 Pandas 系列

TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

【问题讨论】:

    标签: python pandas dataframe typeerror


    【解决方案1】:

    错误是自我解释的,您不能将 str 类型附加到系列类型。做你想做的事,你可以使用:

    import pandas as pd
    
    xls = pd.DataFrame({'coname': ['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo']})
    wharton = pd.DataFrame({'conm': ['lama', 'hippo', 'tiger']})
    
    
    excel = pd.DataFrame()
    
    excel['HQ_LOC'] = wharton['conm'][wharton['conm'].isin(xls['coname'])]
    
    # print(excel)
    
      HQ_LOC
    0   lama
    1  hippo
    
    • wharton['conm'].isin(xls['coname'])

    pandas.Series.isin(values) 检查 Series 中的元素是否包含在 values 中。它返回一个布尔系列,显示系列中的每个元素是否与传递的序列中的元素完全匹配。

    • wharton['conm'][wharton['conm'].isin(xls['coname'])] 用布尔数组索引wharton['conm'],使值保持为真。

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多