Python Pandas 按列值拆分 DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33742588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:52:32  来源:igfitidea点击:

Pandas split DataFrame by column value

pythonpandasdataframeindexingsplit

提问by 146 percent Russian

I have DataFramewith column Sales.

我有DataFrameSales

How can I split it into 2 based on Salesvalue?

如何根据Sales价值将其分成 2 个?

First DataFramewill have data with 'Sales' < sand second with 'Sales' >= s

第一个DataFrame将有数据,'Sales' < s第二个有'Sales' >= s

采纳答案by jezrael

You can use boolean indexing:

您可以使用boolean indexing

df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert maskby ~:

也可以mask通过~以下方式反转:

mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20


print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

回答by Zero

Using groupbyyou could split into two dataframes like

使用groupby您可以拆分为两个数据帧,例如

In [1047]: df1, df2 = [x for _, x in df.groupby(df['Sales'] < 30)]

In [1048]: df1
Out[1048]:
   A  Sales
2  7     30
3  6     40
4  1     50

In [1049]: df2
Out[1049]:
   A  Sales
0  3     10
1  4     20

回答by keryruo

Using "groupby" and list comprehension:

使用“groupby”和列表理解:

Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.

将所有拆分的数据帧存储在列表变量中,并通过索引访问每个分离的数据帧。

DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]

accessing the separated DF like this:

像这样访问分离的 DF:

ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:

像这样访问分离的 DF 的列值:

ansI_chr=ans[i].chr