Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python透视CSV字符串,而不使用pandas或任何类似库_Python_Csv_Dictionary - Fatal编程技术网

使用python透视CSV字符串,而不使用pandas或任何类似库

使用python透视CSV字符串,而不使用pandas或任何类似库,python,csv,dictionary,Python,Csv,Dictionary,你可能会认为这是另一个多余的问题,但我试着把所有类似的问题都问了一遍,到目前为止运气都不好。在我的特定用例中,我不能将pandas或任何其他类似的库用于此操作 这就是我输入的内容 AttributeName,Value Name,John Gender,M PlaceofBirth,Texas Name,Alexa Gender,F SurName,Garden 这是我的预期输出 Name,Gender,Surname,PlaceofBirth John,M,,Texas Alexa,F,Ga

你可能会认为这是另一个多余的问题,但我试着把所有类似的问题都问了一遍,到目前为止运气都不好。在我的特定用例中,我不能将pandas或任何其他类似的库用于此操作

这就是我输入的内容

AttributeName,Value
Name,John
Gender,M
PlaceofBirth,Texas
Name,Alexa
Gender,F
SurName,Garden
这是我的预期输出

Name,Gender,Surname,PlaceofBirth
John,M,,Texas
Alexa,F,Garden,
到目前为止,我已经尝试将输入存储到字典中,然后尝试将其写入csv字符串。但是,它失败了,因为我不知道如何合并缺少的列值条件。这是到目前为止我的代码

  reader = csv.reader(csvstring.split('\n'), delimiter=',')

  csvdata = {}
  csvfile = ''
  for row in reader:
    if row[0] != '' and row[0] in csvdata and row[1] != '':
      csvdata[row[0]].append(row[1])
    elif row[0] != '' and row[0] in csvdata and row[1] == '':
      csvdata[row[0]].append(' ')
    elif row[0] != '' and row[1] != '':
      csvdata[row[0]] = [row[1]]
    elif row[0] != '' and row[1] == '':
      csvdata[row[0]] = [' ']
    
  for key, value in csvdata.items():
    if value == ' ':
      csvdata[key] = []

  csvfile += ','.join(csvdata.keys()) + '\n'
  for row in zip(*csvdata.values()):
    csvfile += ','.join(row) + '\n'
对于上面的代码,我也接受了一些帮助。提前感谢您的建议/建议

编辑#1:更新代码,表示我正在处理csv字符串,而不是csv文件。

这对我很有用:

以open(“in.csv”)作为填充,以open(“out.csv”,“w”)作为输出文件:
incsv,outcsv=csv.reader(infle),csv.writer(outfile)
增加下一行跳过第一行
outcsv.writerows(zip(*incsv))
更新:对于作为字符串的输入和输出:

导入csv,io
将io.StringIO(indata)作为填充文件,io.StringIO()作为输出文件:
incsv,outcsv=csv.reader(infle),csv.writer(outfile)
增加下一行跳过第一行
outcsv.writerows(zip(*incsv))
打印(outfile.getvalue())

您需要的是:

import csv

with open("in.csv") as infile:
    buffer = []
    item = {}

    lines = csv.reader(infile)
    for line in lines:
        if line[0] == 'Name':
            buffer.append(item.copy())
            item = {'Name':line[1]}
        else:
            item[line[0]] = line[1]
    buffer.append(item.copy())

for item in buffer[1:]:
    print item

如果所有属性都不是必需的,我认为@framontb solution需要重新排列,以便在未给出
Name
字段时也能工作。
这是一个免进口的解决方案,它不是超优雅的

我假设您已经有了此表单中的行,其中包含以下列:

lines = [
    "Name,John",
    "Gender,M",
    "PlaceofBirth,Texas",
    "Gender,F",
    "Name,Alexa",
    "Surname,Garden"  # modified typo here: SurName -> Surname
]

cols = ["Name", "Gender", "Surname", "PlaceofBirth"]
我们需要区分一条记录和另一条记录,如果没有必填字段,我能做的最好的事情就是在已经看到属性时开始考虑新记录。
为此,我使用一个临时属性列表
tempcols
,从中删除元素,直到出现错误,即新记录

代码:

csvdata = {k:[] for k in cols}

tempcols = list(cols)
for line in lines:
    attr, value = line.split(",")
    try:
        csvdata[attr].append(value)
        tempcols.remove(attr)
    except ValueError:
        for c in tempcols:  # now tempcols has only "missing" attributes 
            csvdata[c].append("")
        tempcols = [c for c in cols if c != attr]
for c in tempcols:
    csvdata[c].append("")

# write csv string with the code you provided
csvfile = ""
csvfile += ",".join(csvdata.keys()) + "\n"
for row in zip(*csvdata.values()):
    csvfile += ",".join(row) + "\n"

>>> print(csvfile)
Name,PlaceofBirth,Surname,Gender
John,Texas,,M
Alexa,,Garden,F

而如果要根据所需输出对列进行排序:

csvfile = ""
csvfile += ",".join(cols) + "\n"
for row in zip(*[csvdata[k] for k in cols]):
    csvfile += ",".join(row) + "\n"

>>> print(csvfile)
Name,Gender,Surname,PlaceofBirth
John,M,,Texas
Alexa,F,Garden,

我需要创建一个csv字符串来代替csv文件。我得到的输入csv也是csv字符串的形式,我无权使用(打开):(我们可以仅仅通过字符串操作来完成吗?我们也可以使用StringIO来处理输入数据。我们可以使用字符串函数和状态机来完成这一切,但这真的很难。csv比您想象的更难正确解析。最好使用
csv
模块。这就是它的用途。使用缓冲区[1:]列表中,您可以将其保存在csv或whateveris'Name'中。必填项?列AttributeName列中的值不是必填项。