【问题标题】:how to transpose every multiple rows that start with a specific string into columns?如何将以特定字符串开头的每多行转置为列?
【发布时间】:2019-11-05 04:18:03
【问题描述】:

我想问一下如何将每多行转换为列并使用python保存到文本文件中?我在以下部分附加了输入和预期输出。根据输入,我想选择以“数字”开头的每一行,然后转置为列。

最后我想将预期的输出保存到文本文件中。

输入:

number 
12
apple
13
banana
14
number
1
carrot
2
cucumber
3
number 
11
pen
10

预期输出:

number    12     apple     13     banana       14
number    1      carrot    2      cucumber     3
number    11     pen       10

任何帮助将不胜感激。,谢谢!

【问题讨论】:

  • 对不起,我输入了输入,输入的呈现方式是我试图做的,我不知道为什么会这样,请看一下我的图像上传到谷歌驱动器,非常感谢!!
  • 预期输出文件的类型是什么?
  • 嗨,先生,预期的输出文件是.txt格式(文本文件格式)
  • 如果预期的输出文件是 .xlsx 或 .csv 格式(excel 文件格式)也很酷。
  • 你已经尝试了什么?

标签: python dataframe reshape transpose


【解决方案1】:

首先让我们将数据加载到内存中:

with open('input.txt', 'r') as data:
    info = data.read()
info = info.split()

现在让我们将数据配对成(name, number) 元组:

list_of_tuples = [(name, int(info[index+1])) for name, index in enumerate(info)]

现在找到你的行:

list_of_rows = []
cur_row = []
for tuple in list_of_tuples:
    if tuple[0] == 'number':
         if len(cur_row) > 0:
              list_of_rows.append(cur_row)
              cur_row.clear()
         cur_row.append(tuple)
list_of_rows.append(cur_row)

现在将其加载到文本文件中:

with open('out.txt', 'w') as out:
     for row in list_of_rows:
          out.write('\t'.join(row))

代码是经过头脑编译的,所以如果您遇到问题,请告诉我...

【讨论】:

  • 你有 enumerate 向后 - 它返回 index, value 元组。而且我自己还没有测试过,但它似乎会产生重复;我想你想要enumerate(info[::2])
  • 嗨,cuniculus,我已经运行了你的代码,但似乎遇到了其他一些问题,这是错误:``` list_of_tuples = [(name, int(info[index+1 ])) for name, index in enumerate(info)] TypeError: can only concatenate str (not "int") to str ```我还是不知道错误..
  • 好的,wjandrea,我会尝试你的建议,谢谢。顺便说一句,你们如何将代码/数据放在浅灰色的盒子上?我已经尝试过了,但对我来说没有运气......
  • @EdisonToh 实际上我现在正在尝试我的建议,但无法让它发挥作用。我将很快添加另一条评论。对于灰色框,请参阅 Markdown 帮助页面上的 Code and Preformatted Text
  • 所以我更改了list_of_tuples = [(name, int(info[index+1])) for index, name in enumerate(info) if not name.isdigit()],但list_of_rows[[('number', 11)], [('number', 11)], [('number', 11)]]
【解决方案2】:

还有其他关于读写文本文件的问题,所以我把这些问题留给你作为练习。

假设您已经将输入文件加载为records

records = ['number', '12', 'apple', '13', 'banana', '14', 'number', '1', 'carrot', '2', 'cucumber', '3', 'number', '11', 'pen', '10']

您要做的是遍历每个record,如果是'number',则创建一个新行,然后将record 添加到最新行。这段代码就是这样做的:

rows = []
for record in records:
    if record == 'number':
        # Create a new row
        rows.append([])
    # Append to the last row
    rows[-1].append(record)

rows 将是这样的:

[['number', '12', 'apple', '13', 'banana', '14'],
 ['number', '1', 'carrot', '2', 'cucumber', '3'],
 ['number', '11', 'pen', '10']]

【讨论】:

  • @EdisonToh 太好了,乐于助人!如果您认为我的回答最有用,请勾选左侧的复选框,将其标记为“已接受”,并有效地将您的问题标记为“已回答”。
  • 非常感谢您的帮助!!除了勾选左侧的复选框之外,还有其他方式可以给你信用吗?是您答案左侧的复选框指的是“勾号”吗?如果是这样,我已经点击了它。
  • @EdisonToh 是的,您可以通过单击左侧的向上箭头来为您认为有用的任何答案投票。是的,您正确地找到了“接受”按钮。
猜你喜欢
  • 1970-01-01
  • 2013-04-26
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
相关资源
最近更新 更多