我有一个像下面这样的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
未按预期填充。任何帮助将不胜感激。
答案 0 :(得分:0)
我认为您可以先replace
个空格' '
到NaN
,然后apply
自定义函数f
和last_valid_index
。来自Dataframe
Series
和ResultAccount
的输出为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