使用pd.read_csv创建数据框,但已连接列中的数据

问题描述 投票:0回答:1

以下数据是大数据集中的一小部分。

  -.976201  -.737468  -.338866  -.174108  -.388671  -.793479 -1.063547 -1.005576
  -.666256  -.254177   .018064   .069349  -.015640  -.090710  -.111850  -.194042
  -.486229  -.993744 -1.554215 -2.003795 -2.348716 -2.770146 -3.502312 -4.712848
 -6.401421 -8.300894 -9.896770-10.674380-10.444660 -9.438081 -8.065303 -6.594510

我本质上想要做的是将数据转换为数据帧并追加一个时间列,但是,我在集合中的最后一行遇到了麻烦,因为这是连字符所连接的点。数据集中的多行都是这种情况,但我不知道如何解决此问题。最终,我想绘制数据,因此需要删除Motion列的dtype:对象。它给我的数据帧显示在所附图片中,这是我的代码:Dataframe print

import numpy as np
import pandas as pd
time_range = np.arange(0, 500, 0.005)

motion_data = pd.read_csv('data.txt', header = None, sep = "\s+", names = range(0, 8, 1))
motion_frame = pd.DataFrame(motion_data)
motion_frame = motion_frame.stack(dropna=False).reset_index(drop=True).to_frame('Motion')
time = pd.DataFrame(time_range, index = None)
motion_frame['Time'] = time

motion_frame['Motion'].str.split('-', expand=True)
# motion_frame['Motion'].astype('float')

print(motion_frame)
motion_frame.dtypes
python pandas dataframe dataset data-conversion
1个回答
2
投票
查看您的数据,每列宽10个字符。如果为真,则可以使用pandas.read_fwf()方法并指定pandas.read_fwf()

例如:

'widths='

打印:

import numpy as np import pandas as pd time_range = np.arange(0, 500, 0.005) motion_data = pd.read_fwf('data.txt', widths=[10] * 8, names = range(0, 8, 1)) motion_frame = pd.DataFrame(motion_data) motion_frame = motion_frame.stack(dropna=False).reset_index(drop=True).to_frame('Motion') time = pd.DataFrame(time_range, index = None) motion_frame['Time'] = time motion_frame['Motion'] = motion_frame['Motion'].astype('float') print(motion_frame) print(motion_frame.dtypes)

© www.soinside.com 2019 - 2024. All rights reserved.