python保存csv指定列
时间: 2023-08-08 19:08:26 浏览: 72
要保存CSV文件中的指定列,可以使用pandas库。以下是一个示例代码:
```python
import pandas as pd
# 读取CSV文件
df = pd.read_csv('data.csv')
# 选取指定列
selected_columns = ['column1', 'column2'] # 替换为你需要的列名
df_selected = df[selected_columns]
# 保存为新的CSV文件
df_selected.to_csv('selected_columns.csv', index=False)
```
在这个示例中,我们假设有一个名为"data.csv"的CSV文件,然后我们从中选择"column1"和"column2"这两列,并将结果保存为"selected_columns.csv"文件。你可以根据需要修改列名和文件名。
相关问题
python保存csv指定列的数据
要保存 CSV 文件中指定列的数据,你可以使用 Python 的 `csv` 模块来处理。下面是一个示例代码:
```python
import csv
def save_selected_columns(input_file, output_file, selected_columns):
with open(input_file, 'r', newline='') as file:
reader = csv.reader(file)
headers = next(reader) # 读取文件的第一行作为表头
# 确定所选列的索引
selected_indexes = [headers.index(col) for col in selected_columns]
with open(output_file, 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow(selected_columns) # 写入所选列的表头
for row in reader:
selected_row = [row[i] for i in selected_indexes]
writer.writerow(selected_row) # 写入所选列的数据
# 示例用法
input_file = 'input.csv'
output_file = 'output.csv'
selected_columns = ['列名1', '列名2', '列名3']
save_selected_columns(input_file, output_file, selected_columns)
```
在上述代码中,`input_file` 是输入的 CSV 文件路径,`output_file` 是输出的 CSV 文件路径,`selected_columns` 是你想要保存的列的列表。请将代码中的 `'列名1', '列名2', '列名3'` 替换为你要保存的实际列名。
运行该代码后,会读取 `input.csv` 文件中的数据,提取指定的列,并将结果保存到 `output.csv` 文件中。
python保存csv指定列 具体程序 详细
当您需要保存CSV文件中的指定列时,可以使用以下具体程序:
```python
import pandas as pd
def save_selected_columns_to_csv(input_file, output_file, selected_columns):
# 读取CSV文件
df = pd.read_csv(input_file)
# 选取指定列
df_selected = df[selected_columns]
# 保存为新的CSV文件
df_selected.to_csv(output_file, index=False)
# 输入文件路径
input_file = 'data.csv'
# 输出文件路径
output_file = 'selected_columns.csv'
# 选取的列名列表
selected_columns = ['column1', 'column2'] # 替换为你需要的列名
# 调用函数保存指定列到CSV文件
save_selected_columns_to_csv(input_file, output_file, selected_columns)
```
在这个例子中,我们定义了一个函数`save_selected_columns_to_csv`,它接受输入文件路径、输出文件路径和选取的列名列表作为参数。该函数内部使用pandas库来读取输入文件,并根据选取的列名列表选择相应的列。最后,将结果保存为输出文件。您可以根据需要修改输入文件路径、输出文件路径和选取的列名列表。然后,调用该函数即可保存指定列到CSV文件。
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)