【问题标题】:How to merge columns and duplicate row values to match in pandas如何在熊猫中合并列和重复行值以匹配
【发布时间】:2019-07-04 02:47:21
【问题描述】:

我想在“时间”上加入 2 个数据帧,但一个 df 使用 0.25 秒间隔,另一个使用 1 秒间隔。我想将 1 秒间隔 df 的值连接到 0.25 秒间隔 df 并在相应的第二个值内重复值。

以下是我要合并的 2 个数据帧的小 sn-ps:

   time       speaker
   0.25        1
   0.25        2
   0.50        1
   0.50        2
   0.75        1
   0.75        2
   1.00        1
   1.00        2
   1.25        1
   1.25        2
   1.50        1
   1.50        2
   1.75        1
   1.75        2
   2.00        1
   2.00        2

和:

   time  label
    0     10
    1     11
    

我想要:

  time     speaker label
   0.25        1     10
   0.25        2     10
   0.50        1     10
   0.50        2     10
   0.75        1     10
   0.75        2     10
   1.00        1     10
   1.00        2     10
   1.25        1     11
   1.25        2     11
   1.50        1     11
   1.50        2     11
   1.75        1     11
   1.75        2     11
   2.00        1     11
   2.00        2     11

谢谢!

【问题讨论】:

  • This question 对于 pandas 中 resample 方法的不同时间间隔有一些有趣的阅读

标签: python pandas


【解决方案1】:

这里正在使用merge_asof

pd.merge_asof(df1,df2.astype(float),on='time',allow_exact_matches = False)
Out[14]: 
    time  speaker  label
0   0.25        1   10.0
1   0.25        2   10.0
2   0.50        1   10.0
3   0.50        2   10.0
4   0.75        1   10.0
5   0.75        2   10.0
6   1.00        1   10.0
7   1.00        2   10.0
8   1.25        1   11.0
9   1.25        2   11.0
10  1.50        1   11.0
11  1.50        2   11.0
12  1.75        1   11.0
13  1.75        2   11.0
14  2.00        1   11.0
15  2.00        2   11.0

【讨论】:

  • 谢谢@WeNYoBen,这太完美了。
【解决方案2】:

IIUC,这是pd.cut的案例:

df1['label'] = pd.cut(df1['time'], 
                      bins=list(df2['time'])+[np.inf], 
                      labels=df2['label'])

输出:

    time  speaker label
0   0.25        1    10
1   0.25        2    10
2   0.50        1    10
3   0.50        2    10
4   0.75        1    10
5   0.75        2    10
6   1.00        1    10
7   1.00        2    10
8   1.25        1    11
9   1.25        2    11
10  1.50        1    11
11  1.50        2    11
12  1.75        1    11
13  1.75        2    11
14  2.00        1    11
15  2.00        2    11

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 2019-08-25
    • 2017-12-10
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多