python 中的 Int 数组 + 字符串数组的串联(类似于 R 中的 paste() )?

Concatenation of Int array + string array in python (similar to paste() in R)?

我是 python 世界的新手,我一直在利用 R 的矢量化运算,所以我有一个基本问题...

我有 2 个数组,1 个具有 int 个值,另一个具有 string 个值。我想要一个 pandas 系列,将两者串联起来,例如:

0      Enterobact
1        Pseudomo
2        Mycobact
3             Bac
4        Streptoc
5    Propionibact
6       Staphyloc
7           Morax
8        Synechoc
9            Gord
Name: fam, dtype: object

0    7275
1    3872
2    3869
3    1521
4    1408
5    1022
6     877
7     765
8     588
9     578
Name: frequency, dtype: int64

我想要以下内容..:[=​​15=]

Enterobact - 7275
Pseudomo - 3872
Mycobact - 3869
# And so on...

解决python中这个问题的正确方法应该是什么?不是适合 R 用户的方式。非常感谢您...

不确定您实际需要哪种格式的结果,但我会给您两种方法。首先,我假设你的数据存储在两个变量中:

print(fam_column)
print(freq_column)

两个变量的输出正是你所拥有的:

0      Enterobact
1        Pseudomo
2        Mycobact
3             Bac
4        Streptoc
5    Propionibact
6       Staphyloc
7           Morax
8        Synechoc
9            Gord

Name: fam, dtype: object
0    7275
1    3872
2    3869
3    1521
4    1408
5    1022
6     877
7     765
8     588
9     578
Name: frequency, dtype: int64

因此,第一种方法利用了这些列表是数据框列这一事实,我们可以使用 pandas 中的操作。该代码只是将行连接在一起作为字符串,中间是 -:

result = fam_column + ' - ' + freq_column.astype(str)
print(result)

输出:

0      Enterobact - 7275
1        Pseudomo - 3872
2        Mycobact - 3869
3             Bac - 1521
4        Streptoc - 1408
5    Propionibact - 1022
6        Staphyloc - 877
7            Morax - 765
8         Synechoc - 588
9             Gord - 578
dtype: object

在您的问题中,您提到要合并两个数组(在 python 列表中),因此我创建了第二种方法。这个不是首选,因为使用现有的数据框要简单得多。此方法将您的列转换为两个列表,然后在生成器中将它们组合成所需的形式。

list_fam = list(df1['fam'])
list_frequency = list(df2['frequency'])

result = [x + ' - ' + str(y) for x, y in zip(list_fam,list_frequency)]
print(result)

输出如下:

['Enterobact - 7275', 'Pseudomo - 3872', 'Mycobact - 3869', 'Bac - 1521', 'Streptoc - 1408', 'Propionibact - 1022', 'Staphyloc - 877', 'Morax - 765', 'Synechoc - 588', 'Gord - 578']