這是我第一次在這里發帖,這是一個棘手的問題,基本上我有這張表,我有一個病人服用了某種藥物,但缺少某些日期,因為病人一次可以買幾盒,所以我基本上根據患者購買的盒子數量復制了行。這讓我看到了這張表:

在這種情況下,您可以看到重復的行都購買了足夠兩個月的藥物。
我需要做的是按順序轉換日期,但我只能在日期重復時這樣做,所以我不會更改其他患者的原始資料。
我試過這樣的 for 回圈
for index,row in output_table_1.iterrows():
if index == 0:
next
elif output_table_1.loc[index, 'Date'] == output_table_1.loc[index-1, 'Date']:
output_table_1.at[index, 'Date'] = row['Date'] pd.Timedelta(days=28)
else:
output_table_1.at[index, 'Date'] = row['Date']
但它沒有給我我需要的東西,基本上我需要它根據以前的資訊來更改資料,如下所示:
原始資料:
| 日期 | |
|---|---|
| 6 | 2017-01-31 |
| 7 | 2017-01-31 |
| 8 | 2017-02-28 |
| 9 | 2017-02-28 |
| 10 | 2017-03-31 |
| 11 | 2017-03-31 |
| 12 | 2017-04-30 |
| 13 | 2017-04-30 |
第一個回圈:
| 日期 | |
|---|---|
| 6 | 2017-01-31 |
| 7 | 2017-02-31 |
| 8 | 2017-02-28 |
| 9 | 2017-02-28 |
| 10 | 2017-03-31 |
| 11 | 2017-03-31 |
| 12 | 2017-04-30 |
| 13 | 2017-04-30 |
第二個回圈:
| 日期 | |
|---|---|
| 6 | 2017-01-31 |
| 7 | 2017-02-31 |
| 8 | 2017-03-28 |
| 9 | 2017-02-28 |
| 10 | 2017-03-31 |
| 11 | 2017-03-31 |
| 12 | 2017-04-30 |
| 13 | 2017-04-30 |
第三個回圈:
| 日期 | |
|---|---|
| 6 | 2017-01-31 |
| 7 | 2017-02-31 |
| 8 | 2017-03-28 |
| 9 | 2017-04-28 |
| 10 | 2017-03-31 |
| 11 | 2017-03-31 |
| 12 | 2017-04-30 |
| 13 | 2017-04-30 |
最終輸出:
| 日期 | |
|---|---|
| 6 | 2017-01-31 |
| 7 | 2017-02-31 |
| 8 | 2017-03-28 |
| 9 | 2017-04-28 |
| 10 | 2017-05-31 |
| 11 | 2017-06-31 |
| 12 | 2017-07-30 |
| 13 | 2017-08-30 |
等等。
uj5u.com熱心網友回復:
如果您仍在尋找解決方案,可以嘗試以下操作:
def adjust(ser):
if (ser == ser.shift()).any():
one_month = pd.offsets.MonthEnd()
last_month = ser.iat[0]
for i, month in ser.iloc[1:].items():
if month <= last_month:
ser.at[i] = last_month one_month
last_month = ser.at[i]
return ser
df.Date = df.groupby(["Pt", "Drg name"]).Date.transform(adjust)
假設:
- 您的所有日期都是月末日期(在示例中看起來像)。
- 您的示例不具有代表性,因為在多個日期系列中可能存在“差距”:請參閱下面示例中的最后一組。如果這不是必需的,那么有一個更簡單的解決方案。
我添加了條件if (ser == ser.shift()).any()以避免不必要的作業。如果您必須調整大多陣列,那么最好將其洗掉。
結果為
df =
Pt Date Drg name
0 Pt A 2017-01-31 Drg A
1 Pt A 2017-02-28 Drg A
2 Pt A 2017-03-31 Drg A
3 Pt A 2017-04-30 Drg A
4 Pt A 2017-05-31 Drg A
5 Pt A 2017-06-30 Drg A
6 Pt A 2017-01-31 Drg B
7 Pt A 2017-01-31 Drg B
8 Pt A 2017-02-28 Drg B
9 Pt A 2017-02-28 Drg B
10 Pt A 2017-03-31 Drg B
11 Pt A 2017-03-31 Drg B
12 Pt A 2017-04-30 Drg B
13 Pt A 2017-04-30 Drg B
14 Pt B 2020-11-30 Drg B
15 Pt B 2020-11-30 Drg B
16 Pt B 2021-02-28 Drg B
17 Pt B 2021-02-28 Drg B
是
Pt Date Drg name
0 Pt A 2017-01-31 Drg A
1 Pt A 2017-02-28 Drg A
2 Pt A 2017-03-31 Drg A
3 Pt A 2017-04-30 Drg A
4 Pt A 2017-05-31 Drg A
5 Pt A 2017-06-30 Drg A
6 Pt A 2017-01-31 Drg B
7 Pt A 2017-02-28 Drg B
8 Pt A 2017-03-31 Drg B
9 Pt A 2017-04-30 Drg B
10 Pt A 2017-05-31 Drg B
11 Pt A 2017-06-30 Drg B
12 Pt A 2017-07-31 Drg B
13 Pt A 2017-08-31 Drg B
14 Pt B 2020-11-30 Drg B
15 Pt B 2020-12-31 Drg B
16 Pt B 2021-02-28 Drg B
17 Pt B 2021-03-31 Drg B
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370312.html
