[英]return first row with non-null value. if null , then return first row appearance python-pandas
我有一個 pandas dataframe 包含以下數據。 數據按 sessionid、日期時間 (ASC) 排序
df = df.sort_values(['datetime','session_id'],ascending=True)
session_id | 資源 | 約會時間 |
---|---|---|
1 | 2021-01-23 11:26:34.166000 | |
1 | 2021-01-23 11:26:35.202000 | |
2 | 空/南 | 2021-01-23 11:05:10.001000 |
2 | 2021-01-23 11:05:17.289000 | |
3 | 空/南 | 2021-01-23 13:12:32.914000 |
3 | 空/南 | 2021-01-23 13:12:40.883000 |
我想要的結果應該是(來自每個 ++session_id++ 的行,在 ++source++ 列中具有第一個非空值,如果所有 null,則返回第一次出現(case id = 3))
session_id | 資源 | 約會時間 |
---|---|---|
1 | 2021-01-23 11:26:34.166000 | |
2 | 2021-01-23 11:05:17.289000 | |
3 | 空/南 | 2021-01-23 13:12:32.914000 |
函數first_valid_index
和first
以某種方式給了我想要的結果。
find_first_value
:
session_id | 資源 | 約會時間 |
---|---|---|
1 | 2021-01-23 11:26:34.166000 | |
2 | 2021-01-23 11:05:17.289000 |
x = df.groupby(by="session_id")'om_source'].transform(pd.Series.first_valid_index ) newdf = df[df.index==x]
第first
:
它返回第一個非 null 值 ++,但對於分隔的每一列 ++,這不是我想要的
session_id | 資源 | 約會時間 |
---|---|---|
1 | 2021-01-23 11:26:34.166000 | |
2 | 2021-01-23 11:05:10.001000 | |
3 | 空/南 | 2021-01-23 13:12:32.914000 |
newdf = df.groupby(by="session_id").first()
我試圖做這樣的事情,但不幸的是這沒有奏效。
df.groupby(by="session_id")['om_source']
.transform(first if ( pd.Series.first_valid_index is None ) else pd.Series.first_valid_index)
你有什么建議嗎? (我是 pandas 的新手,我仍在嘗試理解其背后的“邏輯”)
在此先感謝您的時間。
您可以像這樣創建一個“幫助”列,然后對 drop_duplicates 進行排序:
df.assign(sorthelp=df['source'] == 'NULL/NAN')\
.sort_values(['sorthelp','datetime','session_id'])\
.drop_duplicates('session_id')
Output:
session_id source datetime sorthelp
3 2 twitter 2021-01-23 11:05:17.289000 False
0 1 facebook 2021-01-23 11:26:34.166000 False
4 3 NULL/NAN 2021-01-23 13:12:32.914000 True
然后你可以刪除幫助列
print(df.assign(sorthelp=df['source'] == 'NULL/NAN')
.sort_values(['sorthelp','datetime','session_id'])
.drop_duplicates('session_id')
.drop('sorthelp', axis=1))
Output:
session_id source datetime
3 2 twitter 2021-01-23 11:05:17.289000
0 1 facebook 2021-01-23 11:26:34.166000
4 3 NULL/NAN 2021-01-23 13:12:32.914000
如果您的時間已經排序,您可以執行以下操作:
print(
df.iloc[
df.groupby("session_id")["source"].apply(
lambda x: x.first_valid_index()
if not x.first_valid_index() is None
else x.index[0]
)
]
)
印刷:
session_id source datetime
0 1 facebook 2021-01-23 11:26:34.166000
3 2 twitter 2021-01-23 11:05:17.289000
4 3 NaN 2021-01-23 13:12:32.914000
或使用:=
運算符(Python 3.8+)
print(
df.iloc[
df.groupby("session_id")["source"].apply(
lambda x: fi
if not (fi := x.first_valid_index()) is None
else x.index[0]
)
]
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.