Pandas - Python - 如何根据另外两列的内容更改一列的内容?
Pandas - Python - How to change the contents of one column based on the content of two others?
我有两个字符串列和一个日期时间列:
我想检查第一个字符串列是否为特定值
然后检查日期时间列是否在某个日期之前
然后将第三个字符串列更新为新值。
我可以创建一个变量来提供与日期时间列相匹配的日期:
import time
june2014 = time.strptime('01-06-14','%d-%m-%y')
我正在寻找可以执行此操作的语法?
您应该提供真实数据,但以下内容应该有效:
df.loc[(df['str1'] == some_string) & (df['time'] < june2014 ), 'str2'] = some_new_str_val
这使用 loc
执行标签索引,然后使用 &
的 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
我有两个字符串列和一个日期时间列:
我想检查第一个字符串列是否为特定值 然后检查日期时间列是否在某个日期之前 然后将第三个字符串列更新为新值。
我可以创建一个变量来提供与日期时间列相匹配的日期:
import time
june2014 = time.strptime('01-06-14','%d-%m-%y')
我正在寻找可以执行此操作的语法?
您应该提供真实数据,但以下内容应该有效:
df.loc[(df['str1'] == some_string) & (df['time'] < june2014 ), 'str2'] = some_new_str_val
这使用 loc
执行标签索引,然后使用 &
的 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