SocratesClub / css

《计算社会科学》课程
https://SocratesClub.github.io/css/
16 stars 4 forks source link

Pandas tricks #7

Open chengjun opened 4 years ago

chengjun commented 4 years ago
d = pd.DataFrame({
    "Disease":["D{}".format(i) for i in range(1,9)],
    "Gene1":[0,0,0,24,0,0,0,4],
    "Gene2":[0,0,17,0,0,32,0,0],
    "Gene3":[25,0,0,0,0,0,0,0],
    "Gene4":[0,0,16,0,0,11,0,0]})

d

image

row_index = d[d['Disease'].isin(['D1', 'D2'])].index
col_names = ['Gene1', 'Gene2']
d.loc[row_index, col_names] +=1
d

image

chengjun commented 4 years ago
def AdjustNeighborCounts(row, race_of_mover, delta):
    # row = 3
    # race_of_mover = "darkred"
    # delta = 1
    curr_x = int(row) % side
    curr_y = np.floor(int(row)/side)
    condition1 = df['x'].isin(range(int(curr_x) - depth, int(curr_x) + depth+1))
    condition2 = df['y'].isin(range(int(curr_y) - depth, int(curr_y) + depth+1))
    condition3 = ~ ((df['x']==curr_x) & (df['y']==curr_y))
    row_index = df[(condition1) & (condition2) & (condition3)].index
    col_index = [race_of_mover, "num.neighbors"]
    df.loc[row_index, col_index]+=delta