假设我有以下数据框:
A B C D
0 foo one 1 10
1 bar one 2 20
2 foo two 3 30
3 bar one 4 40
4 foo two 5 50
5 bar two 6 60
6 foo one 7 70
7 foo two 8 80
现在我可以按第一列分组:grouped = df.groupby('A')
。结果我得到以下DataFrameGroupBy
对象:
A B C D
0 foo [one,two,two,one,two] [1,3,5,7,8] [10,30,50,70,80]
1 bar [one,one,two] [2,4,6] [20,40,60]
现在我想访问特定单元格中的值。我该怎么做?例如,我想从“D”列和'A'=='foo'
(第一行)的行中获取值。换句话说,我想获得[10,30,50,70,80]
。有可能吗?
答案 0 :(得分:7)
你在想这样的事吗?
>>> df
A B C D
0 foo one 1 10
1 bar one 2 20
2 foo two 3 30
3 bar one 4 40
4 foo two 5 50
5 bar two 6 60
6 foo one 7 70
7 foo two 8 80
>>> df.groupby("A").get_group("foo")["D"]
0 10
2 30
4 50
6 70
7 80
Name: D
>>> df.groupby("A").get_group("foo")["D"].tolist()
[10, 30, 50, 70, 80]
答案 1 :(得分:1)
可以通过以下语句:
ValueError: Expected 2D array, got 1D array instead:
array=[8. 4. 6. ... 5. 7. 3.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.