輸入:
A a
B b
C c
D d
E e
預期輸出:
A B C D E
a b c d e
代碼:
dic = {}
with open(input_file, 'r') as input:
for line in input:
block = line.strip().split('\t')[0]
dic[block] = line.strip().split('\t')[1]
with open(output_file, 'w') as ouput:
for key, value in dic.items():
我想在不使用熊貓的轉置功能的情況下將“輸入”更改為“預期輸出”。我在字典中添加了每個字串。那么,如何使用字典提取“預期輸出”?
uj5u.com熱心網友回復:
使用zip:
TEST = [
['A', 'a'],
['B', 'b'],
['C', 'c'],
['D', 'd'],
['E', 'e'],
]
result = list(zip(*TEST))
結果是(格式很好):
[
('A', 'B', 'C', 'D', 'E'),
('a', 'b', 'c', 'd', 'e'),
]
uj5u.com熱心網友回復:
我仍然不完全理解你想要做什么,但讓我們試試這個。
在第一個回圈中,您是dic從Input創建的,對嗎?
dic = {'A':'a','B':'b','C':'c','D':'d','E':'e'}
如果你傳遞dic給pd.DataFramewith index=[0],作為
df = pd.DataFrame(dic, index=[0])
你可以在下面得到一個 DataFrame:
A B C D E
0 a b c d e
但是,如果您想要一個串列,則可以dic按鍵和值將其分隔為:
lsts = [list(dic.keys()), list(dic.values())]
這會給你:
[['A', 'B', 'C', 'D', 'E'], ['a', 'b', 'c', 'd', 'e']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395695.html
上一篇:將字典轉換為多索引資料框
下一篇:帶反斜杠的字串到字典
