![](/img/trans.png)
[英]Python Pandas Dataframe: Take next smaller value based on separate column
[英]Python: Pandas - Separate a Dataframe based on a column value
假設我有一個如下所示的數據幀:
in:
mydata = [{'subid' : 'B14-111', 'age': 75, 'fdg':1.78},
{'subid' : 'B14-112', 'age': 22, 'fdg':1.56},]
df = pd.DataFrame(mydata)
out:
age fdg subid
0 75 1.78 B14-111
1 22 1.56 B14-112
我想根據“age”列將數據幀分成兩個不同的數據幀,如下所示:
out:
df1:
age fdg subid
0 75 1.78 B14-111
df2:
age fdg subid
1 22 1.56 B14-112
我怎樣才能做到這一點?
我們可以使用布爾條件作為過濾器直接執行此操作:
In [5]:
df1 = df[df.age == 75]
df2 = df[df.age == 22]
print(df1)
print(df2)
age fdg subid
0 75 1.78 B14-111
age fdg subid
1 22 1.56 B14-112
但如果你有更多的年齡值,也許你想要對它們進行分組:
In [13]:
# group by the age column
gp = df.groupby('age')
# we can get the unique age values as a dict where the values are the key values
print(gp.groups)
# we can get a specific value passing the key value for the name
gp.get_group(name=75)
{75: [0], 22: [1]}
Out[13]:
age fdg subid
0 75 1.78 B14-111
我們還可以獲取唯一值並再次使用它來過濾df:
In [15]:
ages = df.age.unique()
for age in ages:
print(df[df.age == age])
age fdg subid
0 75 1.78 B14-111
age fdg subid
1 22 1.56 B14-112
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.