python - 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 列中值的存在意味着发生了一个事件,我应该创建一个新列,并将此事件映射到标识列的时间。我试过使用数据透视表,但我觉得它可能不是最好的方法
在此先感谢,真的很难过这个
解决方案
将您的数据框分成两部分并合并它们:
# 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
推荐阅读
- matlab - 从两个向量创建函数句柄以传递给 MATLAB 中的积分函数
- r - 如何标记一系列相同的值
- c# - Net Core 3.0 和桌面应用程序
- c# - 错误:远程服务器返回错误:(500)无效的 WSDL 访问,没有 SOAP 请求预期 C#
- sql - 在多对多(一张表)设计中苦苦挣扎
- python - 在数据框的每一列上使用具有不同功能的不同列上的 apply()
- python - 如何绘制具有不同颜色的不同变量的简单数据框
- ruby-on-rails-5 - 具有嵌套属性的活动记录导入
- php - 使用 self 从同一类的内部方法创建对象
- javascript - 具有最小值和最大值的随机值,并且值偏向于中心值