将多个测量合并到熊猫数据框中

时间:2019-07-10 20:07:46

标签: python python-3.x pandas

我在 *。csv 文件中组织了一些测量,如下所示:

m_number,value
0,0.154
1,0.785
…
55,0.578
NaN,NaN
0,1.214
1,0.742
… 

因此,总是有一组 x 度量值( x 在单个文件中应为常数,但不能保证,我必须检查此数字),以 NaN 行。

将数据读入数据框后,我想对其进行重组以供以后使用:

  m_number    value 1      value 2      value 3      value 4  
0        0      0.154        0.214        0.229        0.234       
1        1      0.785        0.742        0.714        0.771
...
55      55      0.578        0.647        0.597        0.623

每组测量值应为一列。

这是代码段:

split_index = df.index[df_benchmark['id'].isnull()]
df_sliced = pd.DataFrame()
for i, index in enumerate(split_index):
    if i == 0:
        df_sliced = df.loc[0:index - 1].copy()
    else:
        #ToDo: Rename first column to 'value 1' if more than 1 measurement
        temp = df['value'].loc[0:index - 1].copy()
        temp.reset_index(drop=True, inplace=True)
        df_sliced['value '+str(i)] = temp
    df.drop(df.index[0:index - split_index[i - 1]], inplace=True)

该代码有效,但是我不喜欢当前的方法。所以我问是否有更好,更优雅的解决方案。

最好, 朱尔兹

1 个答案:

答案 0 :(得分:0)

您可以使用cumsumset_indexunstack来完成这三行代码:

#Create dummy data with 4 runs of 10 measures
df = pd.DataFrame({'m_number':np.tile(np.arange(10),4), 'value':np.random.random(40)})

#使用条件使用累积量查找首次运行和隐蔽状态,并使用unstack进行创建
MultiIndex列标题
df_u = df.set_index([df ['m_number']。eq(0).cumsum(),df ['m_number']])[['value']]。unstack()

#Use condition to find first run and increament using cumsum and unstack to create  
#MultiIndex column headers (Corrected per comments below)
df_u = df.set_index([df['m_number'], df['m_number'].eq(0).cumsum()])[['value']].unstack()

#Flatten MultiIndex column headers 
df_u.columns = [f'{i}_{j}' for i, j in df_u.columns]

#Display results
df_u

输出:

           value_1   value_2   value_3   value_4
m_number                                        
0         0.919057  0.064409  0.288592  0.742759
1         0.449587  0.867031  0.193493  0.853700
2         0.551929  0.925111  0.895273  0.117306
3         0.487501  0.893696  0.696540  0.381469
4         0.389431  0.818801  0.771516  0.489404
5         0.790619  0.478995  0.023236  0.344112
6         0.015389  0.815073  0.195856  0.628263
7         0.068860  0.483731  0.752803  0.581106
8         0.109404  0.281335  0.330910  0.909965
9         0.695120  0.538676  0.766864  0.247283