【问题标题】:stuck with a simple pandas dataframe looping坚持一个简单的熊猫数据框循环
【发布时间】:2018-02-09 13:13:51
【问题描述】:

我有一个 hdf5 文件,里面有 28 个数据集。每个数据集都有不同的维度。例如,第一个数据集是 [60,8],最后一个是 [60,1]。

我想遍历 HDF5 文件,读取每个数据集中的所有数据并将其写入 pandas 数据帧。最后我应该有一个大小为 [60, 218] 的数据框。到目前为止,我已经尝试了以下代码。但是我的代码挂了。

有人能在我的代码中发现错误并告诉我更好的方法吗?

q=h5py.File('AM_B0_D3.7_2016-04-13T215000.flac.h5', 'r') #reading the hdf5 file
dataset_names_list=[]
q.visit(dataset_names_list.append)#creating a list of datasets in the hdf5 file
ten_min_df= pd.DataFrame()
for i in dataset_names_list:
     x=q[i][:]
     if x.shape[1]>1:
         col1=[i + str(num) for num in range(0, x.shape[1])]
         temp=pd.DataFrame(data=x, columns=col1)
         ten_min_df=ten_min_df.append(temp)
     else:
         col2=[i]
         temp=pd.DataFrame(data=x, columns=col2)
         ten_min_df=ten_min_df.append(temp)

【问题讨论】:

  • 没有数据很难知道,但也许df = pd.concat(dataset_names_list) 应该可以工作。
  • 好的。所以假设我们有这 3 个 numpy 数组。第一个=np.random.rand(3,5),第二个=np.random.rand(3,2),第三个=np.random.rand(3,3)。您将如何在循环中读取这 3 个数组(这些数组不能同时使用,我的意思是它们在循环中一个接一个地可用),然后将其写入按列连接的数据框。我的意思是最后数据框的尺寸应该是 3 行和 10 列 (3,10)。

标签: python python-3.x pandas for-loop dataframe


【解决方案1】:

我认为您需要 arrays 的列表,然后将 numpy.concatenateDataFrame 构造函数一起使用:

np.random.seed(452)

first=np.random.rand(3,5)
print (first)
[[ 0.88642869  0.42677701  0.89968857  0.87976326  0.07758206]
 [ 0.43617027  0.03221375  0.46398119  0.14226246  0.14237448]
 [ 0.22679517  0.60271752  0.85003435  0.5676184   0.87565266]]

second=np.random.rand(3,2) 
print (second)
[[ 0.89830548  0.27066452]
 [ 0.23907483  0.73784657]
 [ 0.09083235  0.98984701]]

third=np.random.rand(3,3)

L = [first, second, third]

df = pd.DataFrame(np.concatenate(L, axis=1))
print (df)
          0         1         2         3         4         5         6  \
0  0.886429  0.426777  0.899689  0.879763  0.077582  0.898305  0.270665   
1  0.436170  0.032214  0.463981  0.142262  0.142374  0.239075  0.737847   
2  0.226795  0.602718  0.850034  0.567618  0.875653  0.090832  0.989847   

          7         8         9  
0  0.837404  0.090284  0.764517  
1  0.564904  0.489809  0.254518  
2  0.426737  0.364310  0.328396  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2017-01-15
    • 1970-01-01
    • 2020-11-20
    • 2020-07-05
    • 2017-10-29
    相关资源
    最近更新 更多