首页 > 解决方案 > 需要帮助在 python 中格式化 csv 文件

问题描述

我有这段代码:

import pandas as pd
import os
import numpy as np


df = pd.read_json (r'Desktop\New_folder\responserate_2020.json')
dfcsv = df.to_csv (r'Desktop\New_folder\responserate_2020.csv', index = None)
dfcsv = dfcsv.rename(columns = {'NAME':'name1', 'state':'STATE'}, inplace = False)

而且我知道在这个片段中我要从 json 到 csv。我正在尝试重命名列名并且我已经尝试过

df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)

而这些似乎都不适合我。

当我打印 CSV 文件时也是如此。看起来像:

                                                        0                     1       2       3           4       5       6      7       8       9
0                                                    NAME                GEO_ID  DRRALL  CRRINT   RESP_DATE  CRRALL  DRRINT  state  county   tract
1          Census Tract 9505.02, Genesee County, New York  1400000US36037950502     0.4    57.5  2020-09-30    74.2     0.4     36     037  950502
2             Census Tract 9506, Genesee County, New York  1400000US36037950600     0.4    50.1  2020-09-30    68.4     0.1     36     037  950600
3             Census Tract 9507, Genesee County, New York  1400000US36037950700     0.0    42.7  2020-09-30    53.7     0.0     36     037  950700
4             Census Tract 9508, Genesee County, New York  1400000US36037950800     0.0    48.2  2020-09-30    60.6     0.0     36     037  950800

我将如何摆脱第一行数字和第一列数字?我是否必须将 csv 转换为数据框?我该怎么做?我知道您可以从 df 转到 csv,但不确定如何以另一种方式进行。

对不起,很长的帖子,我需要去掉第一行数字和第一列数字并重命名一些标题。如果可能的话。我对这一切有点陌生。

标签: pythonpandasdataframe

解决方案


重新标记列

df.columns = ['col1', 'col2','col3']

在执行 pd.read_csv() 时跳过行

df = pd.read_csv(filepath, skiprows=2)

推荐阅读