次の形式で大きな CSV ファイルからデータを抽出しようとしています。「x」はテキストまたは整数の形式のデータであると仮定します。各グループには一意の ID がありますが、グループまたは色ごとに常に同じ数の行があるわけではありません。データはカンマで色から区切られます。
id, x
red, x
green, x
blue, x
black, x
id, x
yellow, x
green,
blue, x
black, x
id, x
red, x
green, x
blue, x
black, x
id, x
red, x
green, x
blue, x
id, x
red, x
green, x
blue, x
black, x
列形式でデータを再配置したいと思います。ID は最初の列で、すべてのデータはコンマで区切られている必要があります。私の目標は、行の最初の単語を読み取って、適切な列に配置することです。
line 0 - ID - red - green - blue - yellow - black
line 1 - x, x, x, , x,
line 2 - , x, x, x, x,
line 3 - x, x, x, , x,
line 4 - x, x, x, , ,
line 5 - x, x, x, , x,
これは私が試していたものです...
readfile = open("db-short.txt", "r")
datafilelines = readfile.readlines()
writefile = open("sample.csv", "w")
temp_data_list = ["",]*7
td_index = 0
for line_with_return in datafilelines:
line = line_with_return.replace('\n','')
if not line == '':
if not (line.startswith("ID") or
line.startswith("RED") or
line.startswith("GREEN") or
line.startswith("BLUE") or
line.startswith("YELLOW") or
line.startswith("BLACK") ):
temp_data_list[td_index] = line
td_index += 1
temp_data_list[6] = line
if (line.startswith("BLACK") or line.startswith("BLACK")):
temp_data_list[5] = line
if (line.startswith("YELLOW") or line.startswith("YELLOW")):
temp_data_list[4] = line
if (line.startswith("BLUE") or line.startswith("BLUE")):
temp_data_list[3] = line
if (line.startswith("GREEN") or line.startswith("GREEN")):
temp_data_list[2] = line
if (line.startswith("RED") or line.startswith("RED")):
temp_data_list[1] = line
if (line.startswith("ID") or line.find("ID") > 0):
temp_data_list[0] = line
if line == '':
temp_data_str = ""
for temp_data in temp_data_list:
temp_data_str += temp_data + ","
temp_data_str = temp_data_str[0:-1] + "\n"
writefile.write(temp_data_str)
temp_data_list = ["",]*7
td_index = 0
if temp_data_list[0]:
temp_data_str = ""
for temp_data in temp_data_list:
temp_data_str += temp_data + ","
temp_data_str = temp_data_str[0:-1] + "\n"
writefile.write(temp_data_str)
readfile.close()
writefile.close()