通过在pandas中查找另一个数据框来填充数据框

时间:2016-06-14 17:53:42

标签: python pandas dataframe ipython nan

我有一个像下面这样的pandas数据帧(df):

AccountName   AccountName2  DateTime
abc           guest         2016-06-10 20:46
              guest         2016-06-10 21:32
def                         2016-06-10 23:11
                            2016-06-10 23:31
ghi                         2016-06-10 24:41

我需要根据上面的数据框导出一个新的数据帧(df1)。 df1应该有2个字段,ResultAccount和DateTime。

if(df["AccountName"] != ' '):
 df1["ResultAccount"] = df["AccountName"]
elif(df["AccountName2] != ' '):
 df1["ResultAccount"] = df["AccountName2"]
else:
 df1["ResultAccount"] = "none"

这是我遵循的方法,但df1未按预期填充。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

我认为您可以先replace个空格' 'NaN,然后apply自定义函数flast_valid_index。来自Dataframe SeriesResultAccount的输出为df.DateTime

import pandas as pd
import numpy as np

df = pd.DataFrame({'AccountName2': {0: 'guest', 1: 'guest', 2: ' ', 3: ' ', 4: ' '}, 
                   'DateTime': {0: '2016-06-10 20:46', 1: '2016-06-10 21:32', 2: '2016-06-10 23:11', 3: '2016-06-10 23:31', 4: '2016-06-10 24:41'}, 
                   'AccountName': {0: 'abc', 1: ' ', 2: 'def', 3: ' ', 4: 'ghi'}})

print (df)
  AccountName AccountName2          DateTime
0         abc        guest  2016-06-10 20:46
1                    guest  2016-06-10 21:32
2         def               2016-06-10 23:11
3                           2016-06-10 23:31
4         ghi               2016-06-10 24:41
df[['AccountName','AccountName2']] = df[['AccountName','AccountName2']].replace(' ',np.nan)

def f(x):
    if x.first_valid_index() is None:
        return 'None'
    else:
        return x[x.first_valid_index()]

ResultAccount = (df[['AccountName','AccountName2']].apply(f, axis=1))

df1 = pd.DataFrame({'ResultAccount':ResultAccount ,'DateTime':df.DateTime}, 
                   columns=['ResultAccount','DateTime'])

print (df1)
  ResultAccount          DateTime
0           abc  2016-06-10 20:46
1         guest  2016-06-10 21:32
2           def  2016-06-10 23:11
3          None  2016-06-10 23:31
4           ghi  2016-06-10 24:41

答案 1 :(得分:0)

您可以使用np.select。它是np.where

的多条件推广
import numpy as np
import pandas as pd
df = pd.DataFrame(
    {'AccountName': ['abc', ' ', 'def', ' ', 'ghi'],
     'AccountName2': ['guest', 'guest', ' ', ' ', ' '],
     'DateTime': ['2016-06-10 20:46', '2016-06-10 21:32', '2016-06-10 23:11', '2016-06-10 23:31', '2016-06-10 24:41']})

conditions = [df['AccountName'] != ' ', df['AccountName2'] != ' ']
choices = [df["AccountName"], df["AccountName2"]]
df['ResultAccount'] = np.select(conditions, choices, default='none')

产量

  AccountName AccountName2          DateTime ResultAccount
0         abc        guest  2016-06-10 20:46           abc
1                    guest  2016-06-10 21:32         guest
2         def               2016-06-10 23:11           def
3                           2016-06-10 23:31          none
4         ghi               2016-06-10 24:41           ghi