首页 \ 问答 \ Pandas:根据布尔列表/字典替换数据帧列(Pandas: Replace dataframe columns based on Boolean list/dict)

Pandas:根据布尔列表/字典替换数据帧列(Pandas: Replace dataframe columns based on Boolean list/dict)

我有两个pandas数据框,我想合并在一起,但不是我在我能够找到的例子中看到的方式。 我有一组“旧”数据和一组“新”数据,两个数据框的形状相同,列名相同。 我做了一些分析并确定我需要创建第三个数据集,从“旧”数据中获取一些列,从“新”数据中获取一些列。 举个例子,假设我有这两个数据集:

df_old = pd.DataFrame(np.zeros([5,5]),columns=list('ABCDE'))
df_new = pd.DataFrame(np.ones([5,5]),columns=list('ABCDE'))

简单地说:

     A    B    C    D    E
0  0.0  0.0  0.0  0.0  0.0
1  0.0  0.0  0.0  0.0  0.0
2  0.0  0.0  0.0  0.0  0.0
3  0.0  0.0  0.0  0.0  0.0
4  0.0  0.0  0.0  0.0  0.0

     A    B    C    D    E
0  1.0  1.0  1.0  1.0  1.0
1  1.0  1.0  1.0  1.0  1.0
2  1.0  1.0  1.0  1.0  1.0
3  1.0  1.0  1.0  1.0  1.0
4  1.0  1.0  1.0  1.0  1.0

我做了一些分析,发现我想要替换B列和D列。 我可以在这样的循环中做到这一点:

replace = dict(A=False,B=True,C=False,D=True,E=False)
df = pd.DataFrame({})
for k,v in sorted(replace.items()):
    df[k] = df_new[k] if v else df_old[k]

这给了我想要的数据:

     A    B    C    D    E
0  0.0  1.0  0.0  1.0  0.0
1  0.0  1.0  0.0  1.0  0.0
2  0.0  1.0  0.0  1.0  0.0
3  0.0  1.0  0.0  1.0  0.0
4  0.0  1.0  0.0  1.0  0.0

但是,老实说这看起来有点笨重,而且我想有一种更好的方法来使用熊猫来做到这一点。 另外,我想保留我的列的顺序,这可能不是像这个示例数据集那样按字母顺序排列,所以排序字典可能不是可行的方法,尽管如果我可以从数据集中提取列名,需要。

有没有更好的方法来使用一些Pandas合并功能?


I have two pandas data-frames that I would like to merge together, but not in the way that I've seen in the examples I've been able to find. I have a set of "old" data and a set of "new" data that for two data frames that are equal in shape with the same column names. I do some analysis and determine that I need to create third dataset, taking some of the columns from the "old" data and some from the "new" data. As an example, lets say I have these two datasets:

df_old = pd.DataFrame(np.zeros([5,5]),columns=list('ABCDE'))
df_new = pd.DataFrame(np.ones([5,5]),columns=list('ABCDE'))

which are simply:

     A    B    C    D    E
0  0.0  0.0  0.0  0.0  0.0
1  0.0  0.0  0.0  0.0  0.0
2  0.0  0.0  0.0  0.0  0.0
3  0.0  0.0  0.0  0.0  0.0
4  0.0  0.0  0.0  0.0  0.0

and

     A    B    C    D    E
0  1.0  1.0  1.0  1.0  1.0
1  1.0  1.0  1.0  1.0  1.0
2  1.0  1.0  1.0  1.0  1.0
3  1.0  1.0  1.0  1.0  1.0
4  1.0  1.0  1.0  1.0  1.0

I do some analysis and find that I want to replace columns B and D. I can do that in a loop like this:

replace = dict(A=False,B=True,C=False,D=True,E=False)
df = pd.DataFrame({})
for k,v in sorted(replace.items()):
    df[k] = df_new[k] if v else df_old[k]

This gives me the data that I want:

     A    B    C    D    E
0  0.0  1.0  0.0  1.0  0.0
1  0.0  1.0  0.0  1.0  0.0
2  0.0  1.0  0.0  1.0  0.0
3  0.0  1.0  0.0  1.0  0.0
4  0.0  1.0  0.0  1.0  0.0

but, this honestly seems a bit clunky, and I'd imagine that there is a better way to use pandas to do this. Plus, I'd like to preserve the order of my columns which may not be in alphabetical order like this example dataset, so sorting the dictionary may not be the way to go, although I could probably pull the column names from the data set if need be.

Is there a better way to do this using some of Pandas merge functionality?


原文:
更新时间:2022-09-07 11:09

最满意答案

只需在您的应用程序中包含所有必需的文件,它将在x86和x64上运行 - 请参阅我的博客文章: http//erikej.blogspot.com/2011/02/using-sql-server-compact-40- with.html

您还可以使用下面的代码来检测您的应用程序是否可以使用运行时,但如果yu在上面实现,则不需要:

        public bool IsV40Installed()
    {
        try
        {
            System.Reflection.Assembly.Load("System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
        }
        catch (System.IO.FileNotFoundException)
        {
            return false;
        }
        try
        {
            var factory = System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlServerCe.4.0");
        }
        catch (System.Configuration.ConfigurationException)
        {
            return false;
        }
        catch (System.ArgumentException)
        {
            return false;
        }
        return true;
    }

Just include all the required files with your app, and it will run on both x86 and x64 - see my blog post here: http://erikej.blogspot.com/2011/02/using-sql-server-compact-40-with.html

You can also use code below to detect if the runtime is available to your app, but not required if yu implement above:

        public bool IsV40Installed()
    {
        try
        {
            System.Reflection.Assembly.Load("System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
        }
        catch (System.IO.FileNotFoundException)
        {
            return false;
        }
        try
        {
            var factory = System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlServerCe.4.0");
        }
        catch (System.Configuration.ConfigurationException)
        {
            return false;
        }
        catch (System.ArgumentException)
        {
            return false;
        }
        return true;
    }

相关问答

更多
  • SQL CE只会间隔刷新到磁盘,并且可以通过连接字符串进行更改: “指定在将所有已提交的事务刷新到磁盘之前的间隔时间(以秒为单位)。如果未指定,则默认值为10.” 不要在连接字符串中包含该设置,您将面临丢失数据的风险: http : //erikej.blogspot.dk/2016/02/sql-server-compact-40-sp1-hotfix.html 您可以通过使用CommitMode为Immediate的SqlCeTransaction包装来强制它进行刷新。 http://erikej.bl ...
  • 在您的参考中使用特定的version = true Use specific version = true in your reference
  • 您想要显示所有产品,但只能将状态为1的产品加起来吗? 如果是这样,我认为您需要在您的加入中使用子查询。 尝试这个: Select a.code, a.Naam, a.Voorraad, isnull(sum(orders.Hoeveelheid)-sum(orders.Voldaan)-sum(orders.Geannuleerd),0) as Besteld from Artikels a left join ( select bd.ArtikelID, bd.BestelID, bd. ...
  • 取决于您的计划的性质。 了解SQL CE最适合部署的客户端应用程序,因为SQL CE可以私下部署 。 首次加载程序时,应检查数据库文件是否已存在。 如果数据库不存在,您应该创建数据库并创建相应的表。 客户端计算机必须安装网络框架! 此外 ,您必须要求最终用户可以使用公共安装 ,或者在应用程序中私下部署相应的类库。 Depends on the nature of your program. Understand that SQL CE is most suitable for deployed client ...
  • EF Core支持SQLite,是的。 EF Core支持SQL Compact,但仅限Windows桌面。 使用Xamarin Forms支持EF Core仍在进行中,请参阅: https : //docs.microsoft.com/en-us/ef/efcore-and-ef6/features EF Core supports SQLite, yes. And SQL Compact is supported with EF Core, but only on Windows desktop. Su ...
  • SqlCeConnection和相关对象不能跨线程共享,这可能就是您所面临的问题。 为每个线程创建一个新对象。 After much experimentation I found that wrapping the database calls inside a transaction solved the problem. So instead of the original code like this... using (AMSDBContext context = CreateDatabaseCo ...
  • 必须授予对相应app_pool用户的读/写访问权限。 在这种情况下, IIS APPPOOL\DefaultAppPool 请注意,必须如图所示指定用户组。 One must grant read/write access to the appropriate app_pool user. In this case, IIS APPPOOL\DefaultAppPool Note that the user group must be specified as shown.
  • 我实际上刚刚在博客上写了一段时间。 http://enterpriseyness.com/2011/11/deploying-an-asp-net-web-application-with-sql-ce-4-entity-framework-without-installation/ 如果您轻松点击Web项目,您将看到“添加可部署的依赖项”菜单项。 另外,不要忘记将SQL CE提供程序工厂添加到Web.config中。 Just to update how we solved this problem, w ...
  • Sql metal不能与sqlce 4.0一起使用(我试过),你必须使用linq2entity或手工编写你的数据对象和POCOS。 或者等到下一个版本的视觉工作室。 我希望微软仍然会支持sqlq4.0的linq2sql,因为它很容易使用。 Sql metal doesnt work with sqlce 4.0 (i tried), you must use linq2entity or code your data object and POCOS by hand. Or wait till the ne ...
  • 只需在您的应用程序中包含所有必需的文件,它将在x86和x64上运行 - 请参阅我的博客文章: http : //erikej.blogspot.com/2011/02/using-sql-server-compact-40- with.html 您还可以使用下面的代码来检测您的应用程序是否可以使用运行时,但如果yu在上面实现,则不需要: public bool IsV40Installed() { try { System.Re ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)