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

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

问题描述

我在Python中使用熊猫有一个20 x 4000的数据框。这些列中的两个列分别命名为 Year quarter 。我想创建一个名为 period 的变量,该变量使 Year = 2000 quarter = 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天全站免登陆