【问题标题】:Python to return specific column using list comprehension or apply()Python使用列表理解或apply()返回特定列
【发布时间】:2019-05-29 13:35:10
【问题描述】:

我正在尝试将 R 代码转换为 Python 代码并停留在这一点上。你能告诉我在 Python 中实现这段代码 sn-p 的最佳方法是什么吗?

only0_0$count =0
for(i in 2:length(only0_0$ID))
{
    only0_0$count[i]=ifelse((only0_0$year[i]-1) %in% 
    clientData$Year[clientData$CUSTOMERID %in% only0_0$ID[i]],1,0)
}

背景:

  1. clientData 和 only0_0 都是 DataFrame。
  2. 客户数据{列:年份、客户 ID、...}
  3. only0_0 {列:年份,ID}
  4. ID 和 CustomerID 都代表同一个东西,在对应的表中不是唯一的。
  5. 仅按 {'ID','year'} 排序 0_0

伪代码:

  1. 在 only0_0 中,创建新列 'count' 将全为零。
  2. for 循环从第二次观察到最后一次,将“count”变量填充为:

    • 从 clientData 中选择所有“CustomerID”,其中“ID” in only0_0 与特定行匹配。
    • 例如only0_0.ID == 3197
    • clientData.CustomerID 将返回 customerID=3197 的所有行 ID
    • 例如最后一步的输出:rowid(或 Python 中的索引){3,11,81,87}
    • 从上一步返回的行 id 中提取相应的年份值
    • 例如最后一步的输出:{2006, 2008, 2009, 2006}

    • 假设:(only0_0.year - 1) == 2008 年的输出

    • 因为 2008 在 {2006, 2008, 2009, 2006},count = 1

如果现在清楚,请告诉我。

【问题讨论】:

  • 你能把它变成伪代码或粗略的C代码吗? (不需要运行)给你一个简短的python解决方案很容易,但如果没有经验,很难阅读r到这种程度。
  • 添加了伪代码。如果有帮助,请告诉我。
  • 你能提供一个示例表(输入和输出)吗(一些更用户友好的变量名称会很有用,但我可以通过输入和输出表来解决)。
  • 也添加了示例。

标签: python r python-3.x


【解决方案1】:

不知道only0_0clientData具体是什么,这很难,但这里有一些sn-ps应该可以帮助你:

我假设 only0_0pandas.DataFrameclientData 字典,因为它不包含统一数据。

例如

import pandas as pd
clientData = {'Year': [..., ...], 'CUSTOMERID_transformed': ....}
only0_0 = pd. DataFrame({'count': [1, 2, 3, ...], 'year': [2010, 2012, 2019, ...]})
only0_0.loc[i, 'count'] = 0
for i in range(1, only0_0.shape[0]):    # i.e. skipping the first row
   only0_0.loc[i, 'count'] = 0 if ... else 1

... = int(1-bool(...))

但我觉得写起来更pythonic

if ...:
    only0_0.loc[i, 'count'] = 0
else:
    only0_0.loc[i, 'count'] = 1

现在对于条件,我认为它是由

组成的
(only0_0.loc[i, 'year'] - i) in clientData['Year'][...]

clientData['CUSTOMERID_transformed'] in only0_0.loc[i, 'ID0_0']

编辑: 你的笔记建议

only0_0.loc[i, 'ID0_0'] in clientData['CUSTOMERID_transformed'] 

我希望这有助于你继续前进。

【讨论】:

  • 谢谢。让我尝试实现这一点。会更新你。
  • 非常感谢。根据您的建议,我得到了答案。
【解决方案2】:

谢谢,我知道了。

    if ((only0_0.year[i] - 1) in (clientData['Year'][clientData['CUSTOMERID_transformed'] == only0_0.loc[i, 'ID0_0']].values)):
        only0_0.loc[i,"count"]=1
    else:
        only0_0.loc[i,"count"]=0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2019-06-20
    • 2018-12-13
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多