首页 > 解决方案 > 无法合并两个 DataFrame。( TypeError: 'NoneType' 类型的对象没有 len() )

问题描述

我正在使用 StackOverflow 的调查数据来分析可以在此处找到的数据。

现在,在删除 NaN 并将原始数据帧的索引重置为之后,我有一个数据帧clear_df

  index DevType ConvertedComp
0   2   Designer;Developer, back-end;Developer, front-...   8820.0
1   3   Developer, full-stack   61000.0
2   5   Data or business analyst;Data scientist or mac...   366420.0
3   8   Database administrator;Developer, back-end;Dev...   95179.0
4   9   Data or business analyst;Data scientist or mac...   13293.0

因此,我使用了 split 函数来形成一个新的数据框,其中 split 'DevType' as temp12

temp12 可以在下面看到。

level_0 level_1 0
0   0   0   Designer
1   0   1   Developer, back-end
2   0   2   Developer, front-end
3   0   3   Developer, full-stack
4   1   0   Developer, full-stack
5   2   0   Data or business analyst

现在,我想使用temp12 的level_0列作为 clean_df 的索引,将clean_df的“ConvertedComp”合并到temp12

预期产出

level_0 level_1 0                         ConvertedComp
    0   0   0   Designer                  8820.0
    1   0   1   Developer, back-end       8820.0
    2   0   2   Developer, front-end      8820.0
    3   0   3   Developer, full-stack     8820.0
    4   1   0   Developer, full-stack     61000.0
    5   2   0   Data or business analyst  366420.0

但我收到一个错误

TypeError:“NoneType”类型的对象没有 len()

您可以通过从此处下载数据集来运行以下代码来复制错误:

df_2019 = pd.read_csv("dataset/developer_survey_2019/survey_results_public.csv")

def split_column_value(ori_df, column_name, separator=';'):
    '''
    INPUT - ori_df  - pandas dataframe -  original dataframe
            column_name - string - the name of the column you would like to splite the value
            separator - string - The is a delimiter. The string splits at this specified separator. If is not provided then ; is the separator.
    OUTPUT - 
            df - pandas dataframe - all value for the column of original dataframe
    '''
    ori_df = ori_df.dropna(subset=['DevType','ConvertedComp'])
    df = pd.DataFrame(ori_df[column_name].str.split(separator).tolist()).stack()
    return df

# splite the DevType colume value
temp1 = split_column_value(df_2019, 'DevType')

temp12 = pd.DataFrame(temp1).reset_index()
temp12.head(20)

clean_df=df_2019.dropna(subset=['DevType','ConvertedComp']).reset_index()[['DevType','ConvertedComp']]
clean_df

# LINE WHICH THROWS THE ERROR
merge_df = temp12.merge(clean_df, right_index=True, right_on='ConvertedComp')

标签: pythonpandasdataframe

解决方案


推荐阅读