熊猫:如何获取最大值和最小值并为每一行写入?

时间:2016-12-14 14:03:28

标签: python pandas max min

我有这样的数据;

>> df
    A  B  C  
0   1  5  1  
1   1  7  1
2   1  6  1
3   1  7  1
4   2  5  1
5   2  8  1
6   2  6  1
7   3  7  1
8   3  9  1
9   4  6  1
10  4  7  1
11  4  1  1

我想根据列A获取B列的最大值和最小值(对于列A的每个相同值,我想在列B中找到最小值和最大值)并且想要在原始列表上写入结果表。我的代码是:

df1 = df.groupby(['A']).B.transform(max)
df1 = df1.rename(columns={'B':'B_max'})
df2 = df.groupby.(['A']).B.transform(min)
df1 = df1.rename(columns={'B':'B_min'})
df3 = df.join(df1['B_max']).join(df2['B_min'])

这是结果。

    A  B  C  B_max  B_min
0   1  5  1           
1   1  7  1  7
2   1  6  1
3   1  4  1           4
4   2  5  1
5   2  8  1  8
6   2  6  1           6
7   3  7  1           7
8   3  9  1  9
9   4  6  1
10  4  7  1  7
11  4  1  1           1

但我希望表格看起来像这样;

    A  B  C  B_max  B_min
0   1  5  1  7        4 
1   1  7  1  7        4
2   1  6  1  7        4
3   1  4  1  7        4
4   2  5  1  8        6
5   2  8  1  8        6
6   2  6  1  8        6
7   3  7  1  9        7
8   3  9  1  9        7
9   4  6  1  7        1
10  4  7  1  7        1
11  4  1  1  7        1

将结果的代码解释为这样

1 个答案:

答案 0 :(得分:2)

我认为您只需要为新列指定值,因为transform返回的String rooms = spinner1.getSelectedItem().toString(); 长度与Series相同:

df
df = pd.DataFrame({
'A': [1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4], 
'B': [5, 7, 6, 7, 5, 8, 6, 7, 9, 6, 7, 1], 
'C': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]})

print (df)
    A  B  C
0   1  5  1
1   1  7  1
2   1  6  1
3   1  7  1
4   2  5  1
5   2  8  1
6   2  6  1
7   3  7  1
8   3  9  1
9   4  6  1
10  4  7  1
11  4  1  1
df['B_max'] = df.groupby(['A']).B.transform(max)
df['B_min'] = df.groupby(['A']).B.transform(min)

print (df)
    A  B  C  B_max  B_min
0   1  5  1      7      5
1   1  7  1      7      5
2   1  6  1      7      5
3   1  7  1      7      5
4   2  5  1      8      5
5   2  8  1      8      5
6   2  6  1      8      5
7   3  7  1      9      7
8   3  9  1      9      7
9   4  6  1      7      1
10  4  7  1      7      1
11  4  1  1      7      1
相关问题