gpt4 book ai didi

python-3.x - 使用 Pandas 将数据从行移动到创建的列 - Python

转载 作者:行者123 更新时间:2023-12-04 23:36:00 25 4
gpt4 key购买 nike

我想使用 Pandas 在文本文件上移动数据,以便为用户解析数据。到目前为止,我能够导入多个文本文件并将数据附加到数据框中并添加标题。我想要做的是将数据移动到正确的列,但问题是所有数据都在同一列上。

这是我的数据:

test2218
math-science-physics
00:00:00:00
00:00:30:00
03-21 04:00:00
28
test2228
math
00:00:00:00
00:00:30:00
03-21 04:00:00
26
test2317
reading-comprehension
00:00:00:00
00:00:30:00
03-21 20:02:00

这就是我希望我的输出的样子:
Test ID     Test Info               Duration_A  Duration_B  Next Use        Participants    
test2218 math-science-physics 00:00:00:00 00:00:30:00 03-21 14:00:00 28
test2228 math 00:00:00:00 00:00:30:00 03-21 14:00:00 26
test2317 reading-comprehension 00:00:00:00 00:00:30:00 04-11 13:30:00 2

我到处找都找不到明确的答案。有人可以帮忙吗?

到目前为止,这是我的代码:
import os, glob, pandas as pd
d_frame = []
c_names = ['Test ID', 'Test Info', 'Duration_A', 'Duration_B', 'Next
Use', 'Participants']
files_list = glob.glob(os.path.join('C:\\test', '*.txt'))

for file in files_list:
if os.stat(file).st_size != 0:
df = pd.read_csv(file, delimiter='\t',header=None, names = c_names)

对此的任何见解将不胜感激。提前致谢!

最佳答案

这是使用 numpy.reshape 执行此操作的简单方法:

import numpy as np
import pandas as pd

pd.DataFrame(np.reshape(df.values, (len(df) // 6, 6)),
columns=['Test ID', 'Test Info', 'Duration_A', 'Duration_B', 'Next Use', 'Participants'])


Test ID Test Info Duration_A Duration_B Next Use Participants
0 test2218 math-science-physics 00:00:00:00 00:00:30:00 03-21 04:00:00 28
1 test2228 math 00:00:00:00 00:00:30:00 03-21 04:00:00 26
2 test2317 reading-comprehension 00:00:00:00 00:00:30:00 03-21 20:02:00 2

关于python-3.x - 使用 Pandas 将数据从行移动到创建的列 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55637188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com