python - Pandas:将多个列值一个接一个地连接起来

标签 python pandas dataframe

我有这个数据框:

    0                     1
0  Bin  Months Since Default
1    1                     0
2    2              0< x <=6
3    3             6< x <=12
4    4            12< x <=24
5    5                   24<

我想创建一个新列“texts”,它将 0 和 1 连接到另一个下面,以便生成的数据框如下所示:

    0                     1    texts
0  Bin  Months Since Default    Bin
1    1                     0     1
2    2              0< x <=6     2
3    3             6< x <=12     3
4    4            12< x <=24     4
5    5                   24<     5
6    NaN                NaN      Months Since Default
7    NaN                NaN      0< x <=6
8    NaN                NaN      6< x <=12
9    NaN                NaN      12< x <=24
10   NaN                NaN      24<

可能吗?

最佳答案

使用DataFrame.meltconcat :

#by all columns
s = df.melt(value_name='texts')['texts']
#if need filter columns by list
#s = df[[0,1]].melt(value_name='texts')['texts']
df = pd.concat([df, s], axis=1)
print (df)
      0                     1                 texts
0   Bin  Months Since Default                   Bin
1     1                     0                     1
2     2              0< x <=6                     2
3     3             6< x <=12                     3
4     4            12< x <=24                     4
5     5                   24<                     5
6   NaN                   NaN  Months Since Default
7   NaN                   NaN                     0
8   NaN                   NaN              0< x <=6
9   NaN                   NaN             6< x <=12
10  NaN                   NaN            12< x <=24
11  NaN                   NaN                   24<

关于python - Pandas:将多个列值一个接一个地连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55277263/

相关文章:

python - 比较并计算两个数字之间相同的数字

python - 创建 Pandas DataFrame 的元素并将其设置为列表

python - Pandas:如何创建一个列,该列指示值何时出现在另一列中预先设定的行数?

python - 文件不是 zip 文件错误,但我没有打开 zip 文件

python - 是否可以在不折叠 Pandas DataFrame 的情况下获得 groupby 样式计数?

python - 无法将 datetime.datetime 与 datetime.date 进行比较

python - 如何从跟踪文件中查找重复序列

python - 确定一个企业名称是否与另一个非常相似 - Python

python - Python Pandas 中的 DataFrame 转换

python - Pandas - 按位类似并计算加权平均值