如何在熊猫数据框中根据列的其他列创建列?

时间:2019-12-02 13:16:38

标签: python pandas

我有一个pandas数据框,我想根据其他列向其添加一列。

这是我的代码:

report["newColumntoCreate"] = report["aColumn"].astype("str") + "-" + report["anotherOne"].astype("str")

有更快的方法吗?还是更好的书写方式?如果线路太长,如何让PEP8要求对其进行检查?

3 个答案:

答案 0 :(得分:2)

另一种方法:

report['newColumntoCreate'] = report['aColumn'].astype(str).str.cat(report['anotherOne'].astype(str), sep='-')

答案 1 :(得分:1)

似乎几乎不可能更快地执行此操作,但是至少可以在两行上做到这一点。

report["newColumntoCreate"] = report["aColumn"].astype("str") \
                      + "-" + report["anotherOne"].astype("str")

答案 2 :(得分:1)

report['newColumntoCreate'] = report[['aColumn', 'anotherOne']].astype(str).apply(lambda x: '-'.join(x), axis=1)