![](/img/trans.png)
[英]Extracting information from multiple JSON files to single CSV file in python
[英]extracting information from rows in csv file
我正在處理一個 csv 文件,該文件在一列中將有一個 ID 號,我已將其保存在這樣的字典中:
身份證回合
1 1
1 2
1 3
2 4
2 5
3 6
ID_rounds = {1: [], 2: [], 3: []}
然后我希望代碼遍歷我的 csv 文件中的每一行,並且對於每一行,將整數添加到字典中的正確列表中。
所以最終的結果看起來像: ID_rounds = {1:{1,2,3], 2:[4,5], 3:[6]}
將您的數據導入一個列表,然后簡單地迭代它,為每次迭代分配字典key
和value
。
with open('tt.csv', 'r') as file:
headers = file.readline()
data = [row.strip().split(',') for row in file.readlines()]
d = {}
for key, value in data:
if key in d.keys():
d[key].append(value)
else:
d[key] = [value]
輸出:
d
{'1': ['1', '2', '3'], '2': ['4', '5'], '3': ['6']}
您還可以為此使用defaultdict
(來自collections
模塊):
from io import StringIO
from collections import defaultdict
data = '''ID Round
1 1
1 2
1 3
2 4
2 5
3 6
'''
# initialize default dict (each dict value is an empty list)
dd = defaultdict(list)
lines = StringIO(data)
# skip header
_ = next(lines)
# process body
for line in lines:
key, value = line.rstrip('\n').split()
key = int(key)
value = int(value)
dd[key].append(value)
# show results
print(dict(dd))
{1: [1, 2, 3], 2: [4, 5], 3: [6]}
嘗試:
df = pd.read_csv('your_csv_file.csv', sep=' ')
result = df.groupby("ID").Round.apply(list).to_dict()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.