从具有多个标识符的元素获取数据帧格式

2024-09-25 02:38:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件,格式如下。假设空格是逗号分隔的。你知道吗

                                    slot0                          slot1  
Serial     Timestamp     Height     Width     Score     Height     Width     Score    ....
FA125       2015_05      215.00     125.01    156.02    235.23     862.23    135.52   ....

这种情况会持续数千行,并重复许多槽#的这种模式。槽#与“高度、宽度和分数”相关,槽的中心是谁。也就是说,slot0对应于第一个高度、宽度和分数,slot1对应于第二个高度、宽度和分数。每个插槽有三个测量值。你知道吗

我很难找到最好的方法把这些数据放到1.数据帧我将槽号与特定的高度、宽度和分数相关联,但特别是序列号或时间戳。你知道吗

我曾经想到过这样的事情,但我是否能做得更好还不清楚。你知道吗

Serial     Timestamp  s0_Height  s0_Width  s0_Score  s1_Height  s1_Width  s1_score  ....
FA125       2015_05    215.00     125.01    156.02     235.23     862.23   135.52   ....

在这种情况下似乎有点尴尬,但如果这是唯一的办法,我想我可以管理。你知道吗

# Maybe something like this?
pd.DataFrame({'FSJ1503007N-ct0': ['20150311_021738', 140, 123, 213]}, ['timestamp', 's0_height', 's0_score', 's0_width'])

请记住,我可以以任何方式修改CSV来实例化数据帧,但问题是我不确定用这个数据创建数据帧的最佳方式。你知道吗

谢谢!你知道吗


Tags: csv数据宽度高度serialwidth分数timestamp
2条回答

这实际上取决于你想对你的数据做什么样的计算。你知道吗

如果您只是跳过第一行,您的csv将被读入为:

  Serial Timestamp  Height   Width   Score  Height.1  Width.1  Score.1  ....
0  FA125   2015_05     215  125.01  156.02    235.23   862.23   135.52  ....

可能足够满足你的需要了。你知道吗

import pandas as pd
import numpy as np
# just to create a string buffer, you don't need this if you have csv file
from io import StringIO  

# replicate your csv file structure
line1 = ','.join(['slot' + str(x) for x in range(3)]) + '\n'
line2 = 'Serial,Timestamp,' + ','.join(['Height', 'Width', 'Score']*3) + '\n'
np.random.seed(0)
data = np.random.randint(100, 1000, size=9)
line3 =  'FA125,2015_5,'+','.join([str(x) for x in data]) + '\n'
csv_buffer = line1+line2+line3

Out[40]: 'slot0,slot1,slot2\nSerial,Timestamp,Height,Width,Score,Height,Width,Score,Height,Width,Score\nFA125,2015_5,784,659,729,292,935,863,807,459,109\n'


# read your file, set the first 2 columns as index, the rest using multi-level column index
level1 = ['slot'+str(x) for x in range(3)]
level2 = ['Height', 'Width', 'Score']
multi_level_columns = pd.MultiIndex.from_product([level1, level2])

df = pd.read_csv(StringIO(csv_buffer), index_col=[0,1], skiprows=[0], header=0)
df.columns = multi_level_columns

Out[62]: 
                  slot0              slot1              slot2            
                 Height Width Score Height Width Score Height Width Score
Serial Timestamp                                                         
FA125  2015_5       784   659   729    292   935   863    807   459   109

# you can reshape the original df 
df.stack(level=0)

Out[63]: 
                        Height  Score  Width
Serial Timestamp                            
FA125  2015_5    slot0     784    729    659
                 slot1     292    863    935
                 slot2     807    109    459

相关问题 更多 >