我想找到满足条件的字典或列表项的索引,并将其写入数据框中的新列。
我从以下设置开始:
import pandas as pd
import numpy as np
df = pd.DataFrame(data = {'col1': ['2018_08', '2008_02','2019_01','2017_04']})
dates = {0: ['2019-01-15 00:00:00', '2019_01', 1, 2019, 0],
-1: ['2018-12-15 00:00:00', '2018_12', 12, 2018, -1],
-2: ['2018-11-15 00:00:00', '2018_11', 11, 2018, -2],
-3: ['2018-10-15 00:00:00', '2018_10', 10, 2018, -3],
-4: ['2018-09-15 00:00:00', '2018_09', 9, 2018, -4],
-5: ['2018-08-15 00:00:00', '2018_08', 8, 2018, -5]}
我想检查数据帧col1
中列df
的值是否包含在字典dates
中。如果是,则返回键或字典中相应列表的最后一个条目。如果不是,则返回NaT或NaN。我尝试过:
df['month_seq'] = np.where(df.col1.isin([dates[i][1] for i in range(0,-6,-1)]), '?' ,pd.NaT)
标识正确的条目,但不返回相应的负数。输出显示为:
col1 month_seq
0 2018_08 ?
1 2008_02 NaT
2 2019_01 ?
3 2017_04 NaT
如果尝试过
[dates[i][1] for i in range(0,-6,-1)].index(df.col1)
返回错误。
在此先感谢您的帮助。
答案 0 :(得分:2)
将map
与字典理解所创建的字典一起使用:
df = pd.DataFrame(data = {'col1': ['2018_08', '2008_02','2019_01','2017_04']})
dates = {0: ['2019-01-15 00:00:00', '2019_01', 1, 2019, 0],
-1: ['2018-12-15 00:00:00', '2018_12', 12, 2018, -1],
-2: ['2018-11-15 00:00:00', '2018_11', 11, 2018, -2],
-3: ['2018-10-15 00:00:00', '2018_10', 10, 2018, -3],
-4: ['2018-09-15 00:00:00', '2018_09', 9, 2018, -4],
-5: ['2018-08-15 00:00:00', '2018_08', 8, 2018, -5]}
d = {v[1]:k for k, v in dates.items()}
print (d)
{'2019_01': 0, '2018_12': -1, '2018_11': -2, '2018_10': -3, '2018_09': -4, '2018_08': -5}
df['new'] = df['col1'].map(d)
print (df)
col1 new
0 2018_08 -5.0
1 2008_02 NaN
2 2019_01 0.0
3 2017_04 NaN
答案 1 :(得分:0)
您可以将apply与适当的功能(在这种情况下为locate
)一起使用:
import pandas as pd
import numpy as np
df = pd.DataFrame(data = {'col1': ['2018_08', '2008_02','2019_01','2017_04']})
dates = {0: ['2019-01-15 00:00:00', '2019_01', 1, 2019, 0],
-1: ['2018-12-15 00:00:00', '2018_12', 12, 2018, -1],
-2: ['2018-11-15 00:00:00', '2018_11', 11, 2018, -2],
-3: ['2018-10-15 00:00:00', '2018_10', 10, 2018, -3],
-4: ['2018-09-15 00:00:00', '2018_09', 9, 2018, -4],
-5: ['2018-08-15 00:00:00', '2018_08', 8, 2018, -5]}
def locate(e, d=dates):
for k, values in dates.items():
if e in values:
return k
return np.nan
result = df['col1'].apply(locate)
print(result)
输出
0 -5.0
1 NaN
2 0.0
3 NaN
Name: col1, dtype: float64