DataFrame 如何同时取出两列的值
时间: 2024-04-11 12:27:09 浏览: 20
要同时取出 DataFrame 中的两列值,可以使用以下方法:
1. 使用方括号 [] 运算符,传入列名作为列表来选择两列。例如,假设 DataFrame 名称为 df,想要选择列名为 "column1" 和 "column2" 的两列,可以使用以下代码:
```python
df[['column1', 'column2']]
```
2. 使用 loc 或 iloc 属性来选择两列。loc 属性用于基于标签进行选择,iloc 属性用于基于位置进行选择。以下是两种方法的示例代码:
使用 loc 属性:
```python
df.loc[:, ['column1', 'column2']]
```
使用 iloc 属性:
```python
df.iloc[:, [0, 1]] # 假设 "column1" 是第一列,"column2" 是第二列
```
这些方法将返回一个包含两列的新 DataFrame。如果你只是想要取出两列的值,并不需要返回 DataFrame,可以将这些方法的结果转换为 NumPy 数组或列表。例如,使用 values 属性将结果转换为 NumPy 数组:
```python
df[['column1', 'column2']].values
```
希望这个回答能够帮到你!如果有任何进一步的问题,请随时提问。
相关问题
pandas把一个dataframe中的两列数据取出组成一个新的dataframe
可以使用下面的方法:
假设有一个名为df的DataFrame,其中有两列数据为'a'和'b':
```
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
```
可以使用下面的代码将这两列数据取出组成一个新的DataFrame:
```
new_df = df[['a', 'b']]
```
这样就可以将DataFrame中的两列数据'a'和'b'取出,并组成一个新的DataFrame。
pandas.core.frame.DataFrame如何取出前两列并转为numpy类型
DAO.insertStudent(newStudent);
response.sendRedirect("list");
}
private void updateStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException可以使用`iloc`方法来取出DataFrame的前两列,再使用`to_numpy()`方法将其转换为numpy数组, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String gender = request,例如:
```python
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': [1, 2,.getParameter("gender");
int age = Integer.parseInt(request.getParameter("age"));
String dormitory = request.getParameter("dormitory");
3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
np_array Student student = new Student(id, name, gender, age, dormitory);
studentDAO.updateStudent(student);
response.sendRedirect("list = df.iloc[:, :2].to_numpy()
print(np_array)
```
输出结果为:
```
[[1 4]
[2");
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter 5]
[3 6]]
```
其中,`iloc[:, :2]`表示取所有行,前两列的数据,即第一列和第二列。
相关推荐
![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)