[英]Put a state on a column if an element change the state in a dataframe with Python
我有下一個 dataframe 有很多元素
代碼 | 地位 | 月 |
---|---|---|
一個 | 積極的 | 1 |
b | 不活躍 | 2 |
c | 積極的 | 3 |
b | 積極的 | 4 |
一個 | 不活躍 | 7 |
c | 積極的 | 8 |
無論如何要創建一個 dataframe 和下一個結果
代碼 | 地位 |
---|---|
一個 | 六月更改為非活動 |
b | 更改為 4 月活動 |
c | 沒有變化 |
或者有報告之類的東西,會很有幫助的
嘗試:
sort_values
“代碼”和“月份”列排序值np.where
在狀態更改時分配操作。drop_duplicates
只保留每個“代碼”的最后一行df = df.sort_values(["code", "Month"])
df["status"] = (np.where((df["code"].eq(df["code"].shift())) &
(df["status"].ne(df["status"].shift())),
"change to "+df["status"].str.lower()+" in "+pd.to_datetime(df["Month"],format="%m").dt.strftime("%B"),
"no changes")
)
output = df.drop_duplicates("code", keep="last").drop("Month", axis=1).reset_index(drop=True)
>>> output
code status
0 a change to inactive in July
1 b change to active in April
2 c no changes
您可以使用groupby
並join
“狀態”和“月”並返回新的 dataframe。 然后您可以拆分和合並這兩列的部分(狀態和月份),最后您可以在loc
和分組 object 的幫助下更改在這兩種情況下都具有“活動”的代碼:
# Convert Month and sort
df['Month'] = pd.to_datetime(df['Month'], format='%m').dt.month_name()
df = df.sort_values(["code", "Month"])
>>> print(df)
code status Month
0 a Active January
1 b Inactive February
2 c Active March
3 b Active April
4 a Inactive July
5 c Active August
# Groupby and join
g = df.groupby(['code']).agg(lambda x: ' '.join(x))
>>> print(g)
status Month
code
a Active Inactive January July
b Inactive Active February April
c Active Active March August
# Combine columns and replace to 'no change'
res = pd.DataFrame('change to ' + g.status.str.split(' ',1).str[1] + ' on ' + g.Month.str.split(' ',1).str[1],columns=['status'])
res.loc[res.index.isin(g[g.status.eq('Active Active')].index),'status'] = 'no change'
>>> print(res)
status
code
a change to Inactive on July
b change to Active on April
c no change
樣本 DF:
{'code': {0: 'a', 1: 'b', 2: 'c', 3: 'b', 4: 'a', 5: 'c'},
'status': {0: 'Active',
1: 'Inactive',
2: 'Active',
3: 'Active',
4: 'Inactive',
5: 'Active'},
'Month': {0: 1, 1: 2, 2: 3, 3: 4, 4: 7, 5: 8}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.