簡體   English   中英

Pandas:如何根據 ID 和條件替換面板數據集中的列值

[英]Pandas: How to replace column values in panel dataset based on ID and condition

所以我有一個看起來像這樣的面板 df:

ID 價值
1 2002年 8
1 2003年 9
1 2004年 10
2 2002年 11
2 2003年 11
2 2004年 12

我想將每個 ID 和所有年份的值設置為 2004 年的值。我該怎么做?

df 應如下所示:

ID 價值
1 2002年 10
1 2003年 10
1 2004年 10
2 2002年 12
2 2003年 12
2 2004年 12

在網上找不到任何東西。 到目前為止,我已經嘗試獲取 2004 年每個 ID 的值,從中創建了一個新的 df,然后將其合並回來。不過,這非常慢。

我們可以為此使用Series.map ,首先我們 select 值並創建我們的映射:

mapping = df[df["year"].eq(2004)].set_index("ID")["value"]
df["value"] = df["ID"].map(mapping)
   ID  year  value
0   1  2002     10
1   1  2003     10
2   1  2004     10
3   2  2002     12
4   2  2003     12
5   2  2004     12

讓我們將對應year不是2004value轉換為 NaN,然后獲取每個 ID 的value

df['value'] = (df.assign(value=df['value'].mask(df['year'].ne(2004)))
               .groupby('ID')['value'].transform('max'))
print(df)

   ID  year  value
0   1  2002   10.0
1   1  2003   10.0
2   1  2004   10.0
3   2  2002   12.0
4   2  2003   12.0
5   2  2004   12.0

另一種方法,對於一些品種。

# Make everything that isn't 2004 null~
df.loc[df.year.ne(2004), 'value'] = np.nan
# Fill the values by ID~
df['value'] = df.groupby('ID')['value'].bfill()

Output:

   ID  year  value
0   1  2002   10.0
1   1  2003   10.0
2   1  2004   10.0
3   2  2002   12.0
4   2  2003   12.0
5   2  2004   12.0

還有另一種方法,有點長,但應該很直觀。 基本上為 ID->value 創建一個查找表,然后使用pandas.merge執行查找。

import pandas as pd

# Original dataframe
df_orig = pd.DataFrame([(1, 2002, 8), (1, 2003, 9), (1, 2004, 10), (2, 2002, 11), (2, 2003, 11), (2, 2004, 12)])
df_orig.columns = ['ID', 'year', 'value']

# Dataframe with 2004 IDs
df_2004 = df_orig[df_orig['year'] == 2004]
df_2004.drop(columns=['year'], inplace=True)
print(df_2004)

# Drop values from df_orig and replace with those from df_2004
df_orig.drop(columns=['value'], inplace=True)
df_final = pd.merge(df_orig, df_2004, on='ID', how='right')
print(df_final)

df_2004:

    ID  value
2   1     10
5   2     12

df_final:

    ID  year     value
0   1   2002     10
1   1   2003     10
2   1   2004     10
3   2   2002     12
4   2   2003     12
5   2   2004     12

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM