我正在嘗試將 2 列的標題添加到我的資料框中并將其另存為 CSV。我的 df 有 99 列,但我只想將標題名稱添加到前 2 列。
當我嘗試這個時
import pandas as pd
import os
for f in csv_files:
headers = ['hello','world']
df = pd.read_csv(f, names = headers, sep = ',')
df.to_csv(r'~/Documents/hi.csv', index = False, header=True)
這將獲取帶有標題的 CSV,但只有前 2 列。我仍然想要其余的資料,但它們上沒有標題或任何默認標題也可以。
當我更改時index = True,它會保存其余的列,但我的標題位于 CSV 的最后 2 列而不是前 2 列,如何切換它們,或確保它們在創建 CSV 時位于前 2 列?
uj5u.com熱心網友回復:
嘗試這個:
index = 0
for f in csv_files:
df = pd.read_csv(f, sep = ',')
old_cols = list(df.columns)[2:]
headers = ['hello','world']
new_cols = headers old_cols
df.columns = new_cols
df.to_csv(f'./{index}.csv', index = False, header=True)
index = index 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360946.html
