python - 使用 Pandas 连接两个或多个变量以创建新变量

标签 python string pandas dataframe concatenation

输入数据集:

Var1     Var2   Var3    Var4

101 XXX       yyyy   12/10/2014

101  XYZ      YTRT  13/10/2014

102  TTY       UUUU  9/9/2014

102  YTY      IUYY   10/10/2014

预期数据集:

Var1     Var2   Var3    Var4         New_Variable

101 XXX       yyyy   12/10/2014       XXX, yyyy

101  XYZ      YTRT  13/10/2014        XYZ, YTRT

102  TTY       UUUU  9/9/2014         TTY, UUUU

102  YTY      IUYY   10/10/2014       YTY, IUYY

如何连接两个或多个字符串变量并创建一个新变量来捕获同一数据集中的连接值?

最佳答案

您可以使用cat方法。

这是一个例子:

>>> df = pd.DataFrame({'a':['x','y','z'], 'b': ['x','y','z'], 'c': ['x','y','z']})
>>> df
   a  b  c
0  x  x  x
1  y  y  y
2  z  z  z

现在,您可以在所选列之一上使用 cat 方法创建新列。指定您想要与 others 参数连接的其他列,并使用 sep 参数指定分隔符:

>>> df["new"] = df.a.str.cat(others=[df.b, df.c], sep=', ')
>>> df
   a  b  c      new
0  x  x  x  x, x, x
1  y  y  y  y, y, y
2  z  z  z  z, z, z

关于python - 使用 Pandas 连接两个或多个变量以创建新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26324192/

相关文章:

python - 使用 ssh 从远程主机访问 localhost API

java - 在没有 split 方法/数组的情况下,如何在 Java 中从字符串中提取整数并将它们加在一起?

c++:将其所有参数连接为字符串的函数

python - 如何对动态数据框进行OLS回归并估计斜率系数?

python - 使用子图时如何使用 matplotlib.pyplot.xticks 或类似的?

python - 水平条形图 : adjusting y axes label size

python - python open语句中的反斜杠错误

python - 在 Pandas 中调整每月时间序列数据

pandas - 在 Pandas 中用 NaN 替换连续的 0

python - Google Drive SDK 未返回 google Docs 格式的 headRevisionId