使用python在excel中将数据从列转置到行

dldeef67  于 2022-11-18  发布在  Python
关注(0)|答案(1)|浏览(220)

我有许多文本文件数据,我选择我的数据从文本和插入到一个Excel文件,但我有一个问题:数据导出在列中,如下所示:

David
1253.2500
2568.000
8566.236 
Jack
3569.00
5269.22
4586.00

但是我想按行输出数据,如下所示:

David 1253.2500 2568.000 8566.236
Jack 3569.00 5269.22 4586.00

编码:

import glob
import pandas as pd
while True:
path = input("Insert location:")
file_list = glob.glob(path + "/*.txt")
df_list = []
for file in file_list:
df = pd.read_csv(file)
df_list.append(df.take([0,-1,-4,-7]))
excl_merged = pd.concat(df_list, ignore_index=False)
#part two of the code
writer = pd.ExcelWriter('Total.xlsx', engine='xlsxwriter')
excl_merged.to_excel(writer, sheet_name='Sheet1', index=False, header=False)
writer.close()
print('success!!')

我试验过许多方法,但都不奏效;例如,我测试了

pandas.transpose()

我试图在Excel中做到这一点,但它不工作太.

pw9qyyiw

pw9qyyiw1#

假设输入如下:

df = pd.DataFrame({'col': ['David', '1253.2500', '2568.000', '8566.236', 'Jack', '3569.00', '5269.22', '4586.00']})

您可以用途:

s = pd.to_numeric(df['col'], errors='coerce')
m = s.isna()

out = (df
   .assign(col=df['col'].where(m).ffill(),
           value=s, index=m.groupby(m.cumsum()).cumcount())
   .loc[~m]
   .pivot(index='index', columns='col', values='value')
  )

print(out)

输出量:

col       David     Jack
index                   
1      1253.250  3569.00
2      2568.000  5269.22
3      8566.236  4586.00

相关问题