python - 在 pandas 中连接字符串列

标签 python pandas

我有一个 pandas 数据框,想要连接两列,同时保持数据框中的所有其他列相同。我根据文档尝试了以下操作:

df['Code2']= df['Code'] + df['Period']

然而,结果似乎几乎适用于某些行。而在其他行中它根本不起作用。

请参阅下面“Code2”列中的结果。

+---------+--------+---------+
|  Code   | Period |  Code2  |
+---------+--------+---------+
| 1000000 |   2017 | 1002017 |
| 1100000 |   2017 | 1102017 |
| 1101000 |   2017 | 1103017 |
| 1101100 |   2017 | 1103117 |
| 1101110 |   2017 | 1103127 |
+---------+--------+---------+

请注意,“期间”列中的值并不全部等于 2017 年。仅在上面的摘录中如此。

期望的结果如下:

+---------+--------+--------------+
|  Code   | Period |    Code2     |
+---------+--------+--------------+
| 1000000 |   2017 | 1000000_2017 |
| 1100000 |   2017 | 1100000_2017 |
| 1101000 |   2017 | 1101000_2017 |
| 1101100 |   2017 | 1101100_2017 |
| 1101110 |   2017 | 1101110_2017 |
+---------+--------+--------------+

最佳答案

您在这里将两列的数字相加。通过将它们转换为字符串,您可以将它们连接起来,例如:

df['Code2'] = df['Code']<b>.astype(str)</b> + df['Period']<b>.astype(str)</b>

这会产生:

>>> df
      Code  Period
0  1000000    2017
1  1100000    2017
2  1101000    2017
3  1101100    2017
4  1101110    2017
>>> df['Code2'] = df['Code'].astype(str) + df['Period'].astype(str)
>>> df
      Code  Period        Code2
0  1000000    2017  10000002017
1  1100000    2017  11000002017
2  1101000    2017  11010002017
3  1101100    2017  11011002017
4  1101110    2017  11011102017

或者如果您想用下划线分隔:

df['Code2'] = df['Code'].astype(str) + <b>'_'</b> + df['Period'].astype(str)

这给了我们:

>>> df['Code2'] = df['Code'].astype(str) + '_' + df['Period'].astype(str)
>>> df
      Code  Period         Code2
0  1000000    2017  1000000_2017
1  1100000    2017  1100000_2017
2  1101000    2017  1101000_2017
3  1101100    2017  1101100_2017
4  1101110    2017  1101110_2017

关于python - 在 pandas 中连接字符串列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59618562/

相关文章:

python - 计算具有多列的 pandas 数据框中的聚合值

pandas - 测试 Pandas 代码

python - 如何制作一组既可以同步又可以异步使用的函数?

python - Heroku 中的客户端请求中断

python - 从列表中删除唯一元素

c# - 从 C# 调用 python 函数

python - 如何修复 PlotlyRequestError?

python - Pandas - 在没有循环的情况下查找两个 DataFrame 之间最近的日期

python - 在多列数据上拟合 MultinomialNB

python - 如何在不丢失列的情况下将列(类别类型)转换为列?