如何根据Python中的条件将其他数据框的值分配给当前数据框?

如何解决如何根据Python中的条件将其他数据框的值分配给当前数据框?

我想根据DatetimeIndex条件将一个数据帧中的值分配给另一个数据帧。

我有这个数据框:(第一个)

date                importance
2006-12-05 10:35:00     HIGH
2006-12-13 02:40:00     LOW

此数据框:(第二个)

index                     value
2006-12-05 08:03:01.985    6
2006-12-05 08:11:34.130    7
2006-12-05 08:20:05.959    6
2006-12-05 08:28:38.104    6
2006-12-05 08:37:02.995    6
2006-12-05 08:45:35.140    5
2006-12-05 08:54:06.969    6
2006-12-05 09:02:59.928    6
2006-12-05 09:11:32.072    6
2006-12-05 09:20:03.901    6
2006-12-05 09:28:36.046    5
2006-12-05 09:37:00.937    5
2006-12-05 09:45:33.082    6
2006-12-05 09:54:04.911    6
2006-12-05 10:02:04.889    6
2006-12-05 10:10:37.034    5
2006-12-05 10:19:08.863    6
2006-12-05 10:27:41.008    5
2006-12-05 10:36:04.953    5
2006-12-05 10:44:37.098    5
.
.
.
2006-12-13 02:06:00.898    1
2006-12-13 02:14:33.043    1
2006-12-13 02:23:04.872    1
2006-12-13 02:31:03.904    1
2006-12-13 02:39:36.048    1
2006-12-13 02:48:07.878    2
2006-12-13 02:56:40.022    5
2006-12-13 03:05:04.914    2
2006-12-13 03:13:37.058    3
2006-12-13 03:22:08.888    6
2006-12-13 03:31:03.108    1
2006-12-13 03:39:34.937    1
2006-12-13 03:48:07.081    1
2006-12-13 03:56:38.911    2
2006-12-13 04:05:04.117    3

最终结果应该是这样:

index                      value    new_value
2006-12-05 08:03:01.985    6        
2006-12-05 08:11:34.130    7        
2006-12-05 08:20:05.959    6        
2006-12-05 08:28:38.104    6
2006-12-05 08:37:02.995    6
2006-12-05 08:45:35.140    5
2006-12-05 08:54:06.969    6
2006-12-05 09:02:59.928    6
2006-12-05 09:11:32.072    6
2006-12-05 09:20:03.901    6
2006-12-05 09:28:36.046    5
2006-12-05 09:37:00.937    5
2006-12-05 09:45:33.082    6
2006-12-05 09:54:04.911    6
2006-12-05 10:02:04.889    6
2006-12-05 10:10:37.034    5
2006-12-05 10:19:08.863    6
2006-12-05 10:27:41.008    5        
2006-12-05 10:36:04.953    5            HIGH
2006-12-05 10:44:37.098    5
.
.
.
2006-12-13 02:06:00.898    1
2006-12-13 02:14:33.043    1
2006-12-13 02:23:04.872    1
2006-12-13 02:31:03.904    1
2006-12-13 02:39:36.048    1            LOW
2006-12-13 02:48:07.878    2
2006-12-13 02:56:40.022    5
2006-12-13 03:05:04.914    2
2006-12-13 03:13:37.058    3
2006-12-13 03:22:08.888    6
2006-12-13 03:31:03.108    1
2006-12-13 03:39:34.937    1
2006-12-13 03:48:07.081    1
2006-12-13 03:56:38.911    2
2006-12-13 04:05:04.117    3

我尝试过:

def getNearestDate(items,pivot):
    return min(items,key=lambda x: abs(x - pivot))

items = second_df.index
for pivot in first_df.date:
    d = getNearestDate(items,pivot)
    print(d)
    second_df.loc[second_df.index == d,'new_value'] = first_df.importance

它会打印以下最接近的日期:

2006-12-05 10:36:04.953000
2006-12-13 02:39:36.048000

因此,这几天应该将“重要性”中的值放入。 另外,在new_value列上,所有内容均为NAN。

您能帮我解决这个问题吗?

解决方法

您已使用loc中的条件 second_df.index == d 并在满足条件的索引处返回true,而不是索引。

代替使用 second_df[second_df.index == d].index.values

,

您已经有了for (int i = 1; i < n; ++i) { if (arr[i - 1] == 0) { insert at i a 0; } } insert at i a 0: // First move the remaining to the right: i .. n-2 ... // Then fill in the zero arr[i] = 0; 所需的遮罩。这样会生成一个pandas.Series,其值second_df.index == d为真,而True为假。您可以False一起使用多个掩码,以获取任何掩码中|=的所有行。只需将该系列作为“ new_value”列添加到第二个数据框即可。

True

如果您确实希望mask = False for pivot in first_df.date: mask |= second_df.index == getNearestDate(second_df.index,pivot) second_df['new_value'] = mask 'X'''True的别名,则还可以在添加系列到数据框。

False

编辑:

如果要获取第一个数据帧的mask = False for pivot in first_df.date: mask |= second_df.index == getNearestDate(second_df.index,pivot) second_df['new_value'] = mask.apply(lambda x: 'X' if bool(x) else '') 值,则可以简单地使用getNearestDate函数来确定哪些行需要该值,然后将它们与第二个数据帧合并。

importance
,

您应该只能使用reindexmerge

# note the method and the tolerance. Change them to whatever works best for your actual data
new_df = df2.merge(df.reindex(df2.index,method='nearest',limit=1,tolerance='2T'),left_index=True,right_index=True)


                         value importance
index                                    
2006-12-05 08:03:01.985      6        NaN
2006-12-05 08:11:34.130      7        NaN
2006-12-05 08:20:05.959      6        NaN
2006-12-05 08:28:38.104      6        NaN
2006-12-05 08:37:02.995      6        NaN
2006-12-05 08:45:35.140      5        NaN
2006-12-05 08:54:06.969      6        NaN
2006-12-05 09:02:59.928      6        NaN
2006-12-05 09:11:32.072      6        NaN
2006-12-05 09:20:03.901      6        NaN
2006-12-05 09:28:36.046      5        NaN
2006-12-05 09:37:00.937      5        NaN
2006-12-05 09:45:33.082      6        NaN
2006-12-05 09:54:04.911      6        NaN
2006-12-05 10:02:04.889      6        NaN
2006-12-05 10:10:37.034      5        NaN
2006-12-05 10:19:08.863      6        NaN
2006-12-05 10:27:41.008      5        NaN
2006-12-05 10:36:04.953      5       HIGH
2006-12-05 10:44:37.098      5        NaN
2006-12-13 02:06:00.898      1        NaN
2006-12-13 02:14:33.043      1        NaN
2006-12-13 02:23:04.872      1        NaN
2006-12-13 02:31:03.904      1        NaN
2006-12-13 02:39:36.048      1        LOW
2006-12-13 02:48:07.878      2        NaN
2006-12-13 02:56:40.022      5        NaN
2006-12-13 03:05:04.914      2        NaN
2006-12-13 03:13:37.058      3        NaN
2006-12-13 03:22:08.888      6        NaN
2006-12-13 03:31:03.108      1        NaN
2006-12-13 03:39:34.937      1        NaN
2006-12-13 03:48:07.081      1        NaN
2006-12-13 03:56:38.911      2        NaN
2006-12-13 04:05:04.117      3        NaN
,

只需进行这些小的更改,希望它就会起作用

loc=[]

    def getNearestDate(items,pivot):
        return min(items,key=lambda x: abs(x - pivot))
    
    items = second_df.index
    for pivot in first_df.date:
        d = getNearestDate(items,pivot)
        loc.append(second_df.set_index('index').index.get_loc(d))
    
    ## Adding Data to your second df   
    second_df['importance']=[]
    for index,locations in enumerate(loc):
        df['importance'][int(location)]=first_df['importance'][index]
,

首先,我们必须保留与原始数据框中的日期相对应的日期:

items = second_df.index
dates = []

for pivot in first_df.date:
    dates.append(getNearestDate(items,pivot))
    
first_df['new_date'] = dates

由于我们不再需要它们,因此可以删除整列:

first_df = first_df.drop(columns="date")

为了使合并生效,我们需要在两个数据帧上都声明索引。

first_df.set_index("new_date",inplace =True)

合并过程如下:

second_df = second_df.merge(first_df,how = "left",right_index=True)

此外,重要的是永远不要让NaN出现在数据框中:

second_df.importance = second_df.importance.fillna(0)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-