我是 python 世界的新手,我一直在利用 R 的矢量化操作,所以我有一個基本問題......
我有 2 個陣列,1 個帶有int值,另一個帶有值string。我想有一個熊貓系列,兩者串聯:
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
我想要以下..:
Enterobact - 7275
Pseudomo - 3872
Mycobact - 3869
# And so on...
哪個應該是在python中解決這個問題的正確方法?不是適合 R 用戶的方式。非常感謝您提前...
uj5u.com熱心網友回復:
不確定您實際需要哪種格式的結果,但我會給您兩種方法。首先,我假設您的資料存盤在兩個變數中:
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']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426077.html
上一篇:只洗掉日本數字laravel
