我有幾個英文單詞串列。如何在 DataFrame 中創建一個列,告訴我每個單詞來自哪個串列。因此,將來隨著從新串列中添加更多單詞,我可以跟蹤單詞來自哪個串列?
list_1 = [['ant', 3] ['bat', 3] ['cat', 3]]
df = pd.DataFrame(list_1, columns = ['word', 'length'], dtype = str)
我如何將 list_2 資料添加到此資料框中并確定資料來自源列下的哪些串列?
list_2 = [['rose', 4] ['tulip', 5] ['lilac', 5] ['daisy', 5]]
預期輸出:
source word length
0 list_1 ant 3
1 list_1 bat 3
2 list_1 cat 3
3 list_2 rose 4
4 list_2 tulip 5
5 list_2 lilac 5
6 list_2 daisy 5
uj5u.com熱心網友回復:
這是我將如何做到這一點,使用字典來保存串列,以及對資料框建構式的一個小理解:
import pandas as pd
list_1 = ['ant', 'bat', 'cat']
list_2 = ['rose', 'tulip', 'lilac', 'daisy']
lists = {'list_1': list_1, 'list_2': list_2}
df = pd.DataFrame([(k,e,len(e)) for k,l in lists.items() for e in l],
columns=['source', 'word', 'length'])
輸出:
source word length
0 list_1 ant 3
1 list_1 bat 3
2 list_1 cat 3
3 list_2 rose 4
4 list_2 tulip 5
5 list_2 lilac 5
6 list_2 daisy 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350195.html
上一篇:我怎樣才能在我的輸出中包含小數?
下一篇:生成一系列日期時間日期
