简体   繁体   English

使用来自另一个 dataframe 的具有特定列值的行创建一个新的数据框

[英]create a new dataframes with rows from another dataframe with specific columns values

I would like to create a new pandas dataframe from an existing dataframe with only rows where specific columns values are bigger than x.我想从现有的 dataframe 创建一个新的 pandas dataframe,其中只有特定列值大于 x 的行。 For example:例如:

df =   A B C
     0 1 0 2
     1 2 1 3
     2 3 3 0
     3 4 2 5

I want to create new_df with only the rows where the values of columns B and C are bigger than 0 which means我想只使用列 B 和 C 的值大于 0 的行创建 new_df

new_df =  A B C
        0 2 1 3
        1 4 2 5

I used the command:我使用了命令:

new_df = df.loc[df['B'] > 0 & df['C'] > 0]

but it doesn't work但它不起作用

You almost had it.你几乎拥有它。 Use parenthesis to enclose conditions:使用括号括起来条件:

new_df = df.loc[(df['B'] > 0) & (df['C'] > 0)]

The binary operators & and |二元运算符&| take precedence over equalities/inequalities.优先于平等/不平等。 So what you were doing was equivalent to:所以你所做的相当于:

new_df = df.loc[(df['B'] > (0 & df['C'])) > 0]

You can use this:你可以使用这个:

df[(df[['B', 'C']] > 0).all(axis=1)]

Output: Output:

   A  B  C
1  2  1  3
3  4  2  5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从另一个数据框行创建列并根据两个数据框的值填充它们 - how to create columns from another dataframe rows and populate them based on values from both dataframes 从另一个 Dataframe 的列迭代创建数据帧 - Create Dataframes iteratively from columns of another Dataframe 使用 for 循环使用 dataframe 名称、来自多个数据帧的行数和列数创建一个新的 dataframe - Create a new dataframe with dataframe name, number of rows and columns from multiple dataframes using for loop 如何使用两个 Pandas 数据帧创建一个新数据帧,其中包含来自一个数据帧的特定行? - How can I use two pandas dataframes to create a new dataframe with specific rows from one dataframe? 访问数据帧字典中的值并创建一个新的 dataframe 与 pandas 中的某些列 - Access values in a dictionary of dataframes and create a new dataframe with certain columns in pandas 通过解析列值为数据框创建新列,并使用来自另一列python的值填充新列 - Create new columns for a dataframe by parsing column values and populate new columns with values from another column python pandas:通过将 DataFrame 行与另一个 DataFrame 的列进行比较来创建新列 - pandas: Create new column by comparing DataFrame rows with columns of another DataFrame 当某些列具有相同的值时,将特定行中的值从一个 DataFrame 替换为另一个 - Replace values in specific rows from one DataFrame to another when certain columns have the same values 比较两个数据框的列并创建一个新的数据框 - Compare columns of two dataframes and create a new dataframe DataFrame 中的新列基于来自另一个 DataFrame 的行和列 - New column in DataFrame based on rows and columns from another DataFrame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM