簡體   English   中英

根據日期列在熊貓數據框中插入行

[英]Insert row in pandas Dataframe based on Date Column

我有一個Dataframe df和一個列表li,我的dataframe列包含:

    Student     Score   Date  
    A             10      15-03-19
    C             11      16-03-19
    A             12      16-03-19
    B             10      16-03-19
    A             9       17-03-19

我的列表包含所有學生的姓名li = [A,B,C]如果某個學生在特定日期還沒有來,則將學生的姓名插入分數值為= 0的數據框中

我的最終數據框應為:

    Student   Score   Date
    A         10      15-03-19
    B         0       15-03-19
    C         0       15-03-19
    C         11      16-03-19
    A         12      16-03-19 
    B         10      16-03-19
    A         9       17-03-19
    B         0       17-03-19
    C         0       17-03-19

DataFrame.reindexMultiIndex.from_product DataFrame.reindex使用:

li = list('ABC')

mux = pd.MultiIndex.from_product([df['Date'].unique(), li], names=['Date', 'Student'])
df = df.set_index(['Date', 'Student']).reindex(mux, fill_value=0).reset_index()
print (df)
       Date Student  Score
0  15-03-19       A     10
1  15-03-19       B      0
2  15-03-19       C      0
3  16-03-19       A     12
4  16-03-19       B     10
5  16-03-19       C     11
6  17-03-19       A      9
7  17-03-19       B      0
8  17-03-19       C      0

另一種方法是使用剩下加入DataFrame.merge和創建幫手據幀product ,最后由替換缺失值fillna

from  itertools import product
df1 = pd.DataFrame(list(product(df['Date'].unique(), li)), columns=['Date', 'Student'])
df = df1.merge(df, how='left').fillna(0)
print (df)
       Date Student  Score
0  15-03-19       A   10.0
1  15-03-19       B    0.0
2  15-03-19       C    0.0
3  16-03-19       A   12.0
4  16-03-19       B   10.0
5  16-03-19       C   11.0
6  17-03-19       A    9.0
7  17-03-19       B    0.0
8  17-03-19       C    0.0

暫無
暫無

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

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