gpt4 book ai didi

python - 将一行/n 列转换为多行/3 列 python-pandas

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:03 44 4
gpt4 key购买 nike

我正在尝试将单行多列 (.csv) 转换为 n-rowsx3columns 并将其保存在新文件(csv 或 txt)中

数据:

51.9596,-115.1437,6.0000,51.9596,-115.1285,6.0000,51.9686,-115.1588,6.0000,51.9686,-115.1437,10.5000,51.9686,-115.1285,10.5000,51.9686,-115.1134,8.0000,51.9776,-115.1891,7.5000,51.9776,-115.1740,7.5000,51.9776,-115.1588,7.5000,51.9776,-115.1437,8.0000,51.9776,-115.1285,8.0000,51.9776,-115.1134,8.0000,51.9866,-115.1891,7.0000

我要:

52.9596,-118.1437,6.0000
51.9596,-115.1285,6.0000
54.9686,-119.1588,6.0000
53.9686,-119.1437,10.5000
54.9686,-117.1285,10.5000
55.9686,-111.1134,8.0000
56.9776,-112.1891,7.5000
57.9776,-117.1740,7.5000
58.9776,-112.1588,7.5000
59.9776,-117.1437,8.0000
50.9776,-114.1285,8.0000
50.9776,-115.1134,8.0000
50.9866,-116.1891,7.0000

代码:

import pandas as pd
df=pd.read_csv('~\datatest\datatest2.csv', sep=',')
for i in len (0, len(df), 3):
df1=df
df1.to_csv('~\datatest\out.csv', sep=',')

最佳答案

据我了解,这应该可以解决问题:

import pandas as pd
df=pd.read_csv('~\datatest\datatest2.csv', sep=',')

#reshaping your dataframe as an array and storing it in df2
df2 = df.values.reshape(int(len(df.columns)/3), 3)

#converting df2 (that's currently an array) to a dataframe
df2 = pd.DataFrame.from_records(df2)

#exporting it
df2.to_csv(your_filepath, separator)

关于python - 将一行/n 列转换为多行/3 列 python-pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53779397/

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