我有一个包含2列的csv文件。以下是他看起来的一瞥:
A, john, robert, simon,peter
B, robert, isiah, elephant
C,james, bond, jack, chuck
我想要的是能够使第一行的每个元素成为字典的键,并使行的其余部分成为值。基本上我希望它看起来像这样:
A B C
john robert james
robert isiah bond
peter elephant jack
chuck
答案 0 :(得分:1)
使用pandas.read_csv()
功能:
示例有效input.csv
内容:
A: john, robert, simon, peter
B: robert, isiah, elephant, dave
C: james, bond, jack, chuck
import pandas as pd
df = pd.read_csv('input.csv', header=None, engine='python', sep='[:,]',
skipinitialspace=True, index_col=0)
result = df.transpose()
print(result)
输出:
0 A B C
1 john robert james
2 robert isiah bond
3 simon elephant jack
4 peter dave chuck
使用pandas.DataFrame.to_dict()
函数将Dataframe转换为字典:
...
result = df.transpose().to_dict(orient='list')
print(result)
输出:
{'B': [' robert', ' isiah', ' elephant', ' dave'], 'A': [' john', ' robert', ' simon', ' peter'], 'C': [' james', ' bond', ' jack', ' chuck']}
答案 1 :(得分:0)
您可以尝试这样的事情:
data_before = [
['A:john', 'robert', 'simon', 'peter'],
['B:robert', 'isiah', 'elephant'],
['C:james', 'bond', 'jack', 'chuck']
]
data_after = {row[0].split(':', 2)[0]: [row[0].split(':', 2)[1]]+row[1:] for row in data_before}