首页 > 解决方案 > Pandas:如果值存在于具有映射条件的特定列中,则创建具有特定时间索引值的新列

问题描述

这是我的输入(熊猫数据框):

timestamp             identification   value   identification_bis  value_bis
2021-10-07 10:00:01   123456789         1000                            
2021-10-07 10:00:05                            123456789            900 
2021-10-07 10:00:10                            123456789            100

这是我想得到的:

timestamp             identification    value    event_time           value_bis
2021-10-07 10:00:01   123456789         1000     2021-10-07 10:00:05  900
2021-10-07 10:00:01   123456789         1000     2021-10-07 10:00:10   100

因此,identification_bis 列中值的存在意味着发生了一个事件,我应该创建一个新列,并将此事件映射到标识列的时间。我试过使用数据透视表,但我觉得它可能不是最好的方法

在此先感谢,真的很难过这个

标签: pythonpandasdataframe

解决方案


将您的数据框分成两部分并合并它们:

# Create a boolean mask
mask = df['identification'] != ''

# Split in 2 dataframes
df1 = df.loc[mask, ['timestamp', 'identification', 'value']]
df2 = df.loc[~mask, ['timestamp', 'identification_bis', 'value_bis']]

# Rename columns for the final output
df2 = df2.rename(columns={'identification_bis': 'identification',
                          'timestamp': 'event_time'})

# Merge dataframes on right
out = df1.merge(df2, how='right', on='identification')

注意:这里的关键是布尔掩码。我使用空字符串来确定每行应该放在哪个数据框中。你可以使用任何你想要的面具,但想法还是一样的。

输出:

>>> out
             timestamp identification value           event_time value_bis
0  2021-10-07 10:00:01      123456789  1000  2021-10-07 10:00:05       900
1  2021-10-07 10:00:01      123456789  1000  2021-10-07 10:00:10       100

推荐阅读