找到dataframe中所有元素均为True的所有行,生成一个新的dataframe
时间: 2024-02-26 19:57:24 浏览: 22
好的,我会为您解答此问题。
假设您的原始DataFrame为df,您可以按照以下步骤获取所有元素均为True的行:
```python
# 生成随机数据
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame(np.random.randint(0, 2, size=(5, 5)).astype(bool))
# 获取所有元素均为True的行
mask = df.all(axis=1)
new_df = df[mask]
print(new_df)
```
结果会输出一个新的DataFrame,其中包含所有元素均为True的行。
请注意,`all(axis=1)`的作用是沿着行的方向,检查每一行是否所有元素都为True。如果您需要检查列,请使用`all(axis=0)`。
相关问题
如何将一个元素appendix到dataframe中
您可以使用 pandas 库中的 DataFrame 的 append 方法,将需要添加的元素作为 DataFrame 添加到原有的 DataFrame 中。具体操作如下:
1. 创建需要添加的 DataFrame,例如:
```
new_row = {'col1': val1, 'col2': val2, ...}
new_df = pd.DataFrame(columns=['col1', 'col2', ...])
new_df = new_df.append(new_row, ignore_index=True)
```
2. 将新的 DataFrame 添加到原有的 DataFrame 中,例如:
```
df = df.append(new_df, ignore_index=True)
```
其中,`ignore_index` 参数表示忽略原有 DataFrame 的索引,重新生成一个索引。
请注意,`append` 方法会返回一个新的 DataFrame,而不是直接在原有 DataFrame 中添加新的行。如果需要修改原有的 DataFrame,请将返回的 DataFrame 赋值给原有 DataFrame。
dataframe怎么查找一行字符全为TRUE的行,返回全为TRUE的行形成的dataframe
假设您的DataFrame为`df`,您可以使用以下方式来查找一行字符全为True的行,并返回包含这些行的新DataFrame:
```python
# 生成示例数据
import pandas as pd
data = {'A': [True, False, True],
'B': [True, True, True],
'C': [True, True, False]}
df = pd.DataFrame(data)
# 查找所有字符全为True的行
mask = (df == True).all(axis=1)
new_df = df[mask]
print(new_df)
```
这里我们使用`==`操作符将DataFrame中的所有元素与`True`进行比较,返回一个布尔类型的DataFrame。然后,我们使用`all(axis=1)`方法沿着行的方向检查每一行是否每个元素都为`True`。最后,我们使用这个布尔类型的掩码过滤原始的DataFrame,得到新的DataFrame,其中只包含所有字符都为`True`的行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)