【问题标题】:Pandas - Python - How to change the contents of one column based on the content of two others?Pandas - Python - 如何根据另外两列的内容更改一列的内容?
【发布时间】:2015-04-22 14:59:05
【问题描述】:

我有两个字符串列和一个日期时间列:

我想检查第一个字符串列是否为某个值 然后检查日期时间列是否在某个日期之前 然后将第三个字符串列更新为新值。

我可以创建一个变量来提供日期以匹配日期时间列:

import time
june2014 = time.strptime('01-06-14','%d-%m-%y')

我正在寻找可以做到这一点的语法?

【问题讨论】:

  • 日期时间对象可以轻松比较:'datetimeObject1 > datetimeObject2'

标签: python string datetime pandas


【解决方案1】:

您应该提供真实数据,但以下应该有效:

df.loc[(df['str1'] == some_string) & (df['time'] < june2014 ), 'str2'] = some_new_str_val

这使用 loc 执行标签索引,然后使用 &amp; 的 2 个条件,因为我们正在比较数组和括号,因为运算符优先级。

例子:

In [4]:
# create some dummy data
import datetime as dt
df = pd.DataFrame({'str1':['hello', 'python', 'goodbye'], 'str2':['','',''], 'date':[dt.datetime(2013, 3, 4), dt.datetime.now(), dt.datetime(2014,7,14)]})
df

Out[4]:
                        date     str1 str2
0        2013-03-04 00:00:00    hello     
1 2015-02-20 20:19:34.224030   python     
2        2014-07-14 00:00:00  goodbye     

In [7]:
# create our date for comparison
june2014 = dt.datetime(2014, 6, 1)
df.loc[(df['str1'] == 'hello') & (df['date'] < june2014 ), 'str2'] = 'updated'
df

Out[7]:
                        date     str1     str2
0        2013-03-04 00:00:00    hello  updated
1 2015-02-20 20:19:34.224030   python         
2        2014-07-14 00:00:00  goodbye  

【讨论】:

  • 嘿,谢谢,这太棒了。我想知道(因为我收到一个错误)它在哪里显示“SettingWithCopyWarning” - 我被警告说“正在尝试在 DataFrame 的切片副本上设置一个值。”这是否意味着新值仅设置为 Dataframe 的副本或实际 Dataframe?
  • 是的,这是正确的,您需要使用 locilocix 进行索引,以确保分配发生在视图上,请参阅文档:pandas.pydata.org/pandas-docs/stable/…
猜你喜欢
  • 2020-10-29
  • 1970-01-01
  • 2015-06-15
  • 2016-06-13
  • 2021-10-30
  • 2023-01-08
  • 2020-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多