Pandas - 列排序更改
Pandas - Column sorting changes
我正在尝试将一组 csv 文件合并到一个 Dataframe 中。在此过程中,我创建了一个名为 Time_Created 的新列,我试图将其作为 Dataframe 的第一列。
df_v1 = pd.concat([pd.read_csv(f) for f in updatedfiles_1], sort=True)
cols = df_v1.columns.tolist()
print(cols)
cols.insert(0, cols.pop(cols.index('Time_Created')))
print(cols) <-- This shows the columns as expected
df_v1.to_csv('file.csv')
我看到在保存到 csv 之前打印列时,列已根据需要进行了修改,但是当我打开保存的 csv 时,列排序发生了变化。
下面给出了源中列的顺序:
Name,Price,Quanity,Time_Created
我要分类的序列:
Time_Created,Name,Price,Quanity
谁能指导我为什么输出文件更改了列排序。谢谢
尝试使用 df_v1[['Time_Created', 'Name', 'Price', 'Quanity']].to_csv(...)
我相信你很接近。您实际上从未将数据框的列设置为修改后的顺序。你可以做这样的事情,它应该可以工作。
df_v1 = pd.concat([pd.read_csv(f) for f in updatedfiles_1],
sort=True)
cols = df_v1.columns.tolist()
print(cols)
cols.insert(0, cols.pop(cols.index('Time_Created')))
print(cols) <-- This shows the columns as expected
df_v1[cols].to_csv('file.csv') <-Here you tell it to send df_v1 in [cols] order
如果最后一个 print(cols)
是您想要的顺序,那么您可以在发送 df_v1
to_csv.
时使用它
我正在尝试将一组 csv 文件合并到一个 Dataframe 中。在此过程中,我创建了一个名为 Time_Created 的新列,我试图将其作为 Dataframe 的第一列。
df_v1 = pd.concat([pd.read_csv(f) for f in updatedfiles_1], sort=True)
cols = df_v1.columns.tolist()
print(cols)
cols.insert(0, cols.pop(cols.index('Time_Created')))
print(cols) <-- This shows the columns as expected
df_v1.to_csv('file.csv')
我看到在保存到 csv 之前打印列时,列已根据需要进行了修改,但是当我打开保存的 csv 时,列排序发生了变化。
下面给出了源中列的顺序:
Name,Price,Quanity,Time_Created
我要分类的序列:
Time_Created,Name,Price,Quanity
谁能指导我为什么输出文件更改了列排序。谢谢
尝试使用 df_v1[['Time_Created', 'Name', 'Price', 'Quanity']].to_csv(...)
我相信你很接近。您实际上从未将数据框的列设置为修改后的顺序。你可以做这样的事情,它应该可以工作。
df_v1 = pd.concat([pd.read_csv(f) for f in updatedfiles_1],
sort=True)
cols = df_v1.columns.tolist()
print(cols)
cols.insert(0, cols.pop(cols.index('Time_Created')))
print(cols) <-- This shows the columns as expected
df_v1[cols].to_csv('file.csv') <-Here you tell it to send df_v1 in [cols] order
如果最后一个 print(cols)
是您想要的顺序,那么您可以在发送 df_v1
to_csv.