pandasDataFrame读和写csv文件

从.csv文件读数据

import pandas as pd

# 从CSV文件中读取数据
train_df = pd.read_csv("datasets/train01.csv")
val_df = pd.read_csv("datasets/val01.csv")
test_df = pd.read_csv("datasets/test01.csv")

# 显示数据框的前几行,确保数据已成功加载
print("Train Data:")
print(train_df.head())

print("\nValidation Data:")
print(val_df.head())

print("\nTest Data:")
print(test_df.head())

把数据写到.csv文件

# 假设你有一个名为output_df的DataFrame
output_df = pd.DataFrame({
    'Column1': [1, 2, 3],
    'Column2': ['A', 'B', 'C']
})

# 将DataFrame写入CSV文件
output_df.to_csv("output_file.csv", index=False)

train_df[["label", "cutword"]].to_csv("datasets/train01.csv", index=False)
val_df[["label", "cutword"]].to_csv("datasets/val01.csv", index=False)
test_df[["label", "cutword"]].to_csv("datasets/test01.csv", index=False)

你可能感兴趣的:(python,pandas,机器学习)