合并 pandas 数据框中的两列文本 [英] Combine two columns of text in pandas dataframe

查看:42
本文介绍了合并 pandas 数据框中的两列文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中使用 Pandas 有一个 20 x 4000 的数据帧.其中两列名为Yearquarter.我想创建一个名为 period 的变量,它使 Year = 2000quarter= q2 变成 2000q2.

I have a 20 x 4000 dataframe in Python using pandas. Two of these columns are named Year and quarter. I'd like to create a variable called period that makes Year = 2000 and quarter= q2 into 2000q2.

有人可以帮忙吗?

推荐答案

如果两列都是字符串,可以直接拼接:

If both columns are strings, you can concatenate them directly:

df["period"] = df["Year"] + df["quarter"]

如果其中一列(或两列)不是字符串类型,您应该先转换它(它们),

If one (or both) of the columns are not string typed, you should convert it (them) first,

df["period"] = df["Year"].astype(str) + df["quarter"]

执行此操作时要注意 NaN!


如果需要连接多个字符串列,可以使用agg:

df['period'] = df[['Year', 'quarter', ...]].agg('-'.join, axis=1)

-"在哪里是分隔符.

这篇关于合并 pandas 数据框中的两列文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆