【问题标题】:How to replicate number of rows in dataframe1 to match n rows in dataframe 2 in pandas如何复制dataframe1中的行数以匹配pandas中dataframe 2中的n行
【发布时间】:2020-04-24 02:55:52
【问题描述】:

几个月前我刚开始学习 Python,也刚开始使用 StackOverflow,请多多包涵:
我们有两个数据框:

df1:

    0.1,0.2,0.3,0.4  
    1.0,2.0,3.0,4.0
    6.0,7.0,8.0,9.0 

df2:

    Sequence, dataset_ID  
    1,1  
    2,4  
    10,5

我正在使用 python iterrows 函数将 df1 转置为:

for ind,row in df1.iterrows():
    row.to_csv(path+'\df1Transposed')

df1转置:

    0.1,1.0
    0.2,2.0  
    0.3,3.0  
    0.4,4.0
    0.1,6.0
    0.2,7.0  
    0.3,8.0  
    0.4,9.0

我正在尝试找到一种对 df2 中的每一行进行分组/复制以匹配 df1 转置的行数的好方法。例如,df 1 中的 1 个转置标题和行在 df1Transposed (0.1-0.4) 中创建 4 行和 2 列,并为 df1 中的下一行再次重复。所以 df2 中的第一行应该重复 4 次,然后第二行应该再重复 4 次。

dfout:

Sequence, dataset_ID,V,I
1,1,0.1,1.0
1,1,0.2,2.0  
1,1,0.3,3.0  
1,1,0.4,4.0  
2,4,0.1,6.0  
2,4,0.2,7.0  
2,4,0.3,8.0  
2,4,0.4,9.0  

【问题讨论】:

  • df2 中的第三行发生了什么?
  • 对于转置部分,你可以用这个避免迭代:pd.concat([df1.iloc[:2].T, df1.iloc[::2].T.set_axis([0,1],axis=1)],ignore_index=True)
  • 抱歉,我们可以暂时忽略第三行 - 显示的只是我整个数据框的一部分

标签: python python-3.x excel pandas csv


【解决方案1】:

你可以使用numpy的repeat和arange的组合来获取索引,然后水平连接两个数据框。

首先,感谢@sammywemmy 方便的单线:

df1_T = pd.concat([df1.iloc[:2].T,
                   df1.iloc[::2].T.set_axis([0,1],axis=1)],ignore_index=True)

第二次获取转置数据帧的长度,从df2中选择要包含的行数,使用上面提到的函数:

df_1_l = df1_T.shape[0]
no_rows_from_df2 = 2
index = np.repeat(np.arange(no_rows_from_df2), df_1_l//rows_df2)

df3 = pd.concat([df1_T.reset_index(drop=True),
             df2.iloc[index].reset_index(drop=True)], axis=1)
df3

#     0 1   Sequence  dataset_ID
# 0 0.1 1.0   1       1
# 1 0.2 2.0   1       1
# 2 0.3 3.0   1       1
# 3 0.4 4.0   1       1
# 4 0.1 6.0   2       4
# 5 0.2 7.0   2       4
# 6 0.3 8.0   2       4
# 7 0.4 9.0   2       4

这很有效,因为 df1_T 的长度是 df2 中所选行数的倍数,例如,如果您想重复行 0,1,2,那么 df1 的长度应该是 3, 6, 9, 12 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 2021-12-03
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多