Python 大熊猫0.16+;如何使用变量来指示列名来添加列?
正如您在这个问题中所看到的,在Pandas 0.16+中添加列的最佳方法是Python 大熊猫0.16+;如何使用变量来指示列名来添加列?,python,pandas,Python,Pandas,正如您在这个问题中所看到的,在Pandas 0.16+中添加列的最佳方法是 df = df.assign(new_column = Something) 其中new_column是新列的文字名称(即使它不是以字符串形式写入) 这对我来说是个问题,因为我想添加许多列,这些列的名称由变量指定 我试过这个: for col in df.columns: new_col_name = col + "_nancount" test = test.assign(new
df = df.assign(new_column = Something)
其中new_column是新列的文字名称(即使它不是以字符串形式写入)
这对我来说是个问题,因为我想添加许多列,这些列的名称由变量指定
我试过这个:
for col in df.columns:
new_col_name = col + "_nancount"
test = test.assign(new_col_name = test[col].isna().sum())
它不起作用:这样,只添加了一列(名为“new\u col\u name”)
预期结果是,给定一个具有列[“a”、“B”、“C”]的表,该表将具有列[“a”、“B”、“C”、“a_nancount”、“B_nancount”、“C_nancount”]
我该怎么做呢?根据此回复的内容,我认为最好的解决方案如下:
df = df.assign(**{col1: Something, col2: Something})
就我而言:
new_col_dict = {}
for col in df.columns:
new_col_dict[col + "_nancount"] = test[col].isna().sum()
test = test.assign(**new_col_dict)