python - 将数据框附加到excel
问题描述
我已将 excel 读入一个数据框,如下所示:
df =
Item Questions Answer
1 First name Alex
1.1 Age 43
1.2 Nationality English
etc....
我有许多类似的 excel 文件,例如这些我打算读入数据帧的文件,但是我想将所有这些文件整理到一个单独的 excel 中。我不想包括所有列,所以对于上面的数据框,我希望它在添加到单独的 excel 后看起来像下面这样:
First Name Age Nationality
Alex 43 English
另外,我如何将其他类似的数据框添加到这个单独的 excel 中,我认为它会使用 append,但我不太确定该怎么做
解决方案
您需要遍历每个 excel 表(读入它们)并首先旋转或转置数据框以获得所需的列格式(有多种方法可以做到这一点),然后将其连接到单独的单个数据框:
total_dataframe = pd.DataFrame() #initialize empty table
for file in my_excel_files:
df = pd.read_csv(file)
df = pd.DataFrame(df.values.T) #transpose the table
headers = df.iloc[0] #Make first row the column headers
new_df = pd.DataFrame(df.values[1:], columns=headers)
total_dataframe = pd.concat([total_dataframe, new_df]) #append to final table
当然有更优雅的方法可以做到这一点,但我认为这很清楚地打破了这个过程。
推荐阅读
- pycharm - PyCharm 安全删除功能
- python - 使用 64 位训练的 Scikits-Learn RandonForest 并在 64 位 PyCharm 中打开时出错
- swift - 如何在保持 LiDAR 调试网格的同时禁用摄像头馈送?
- c - 多个目标但相同的依赖项
- python - Python Pandas - 将 2D df 转换为 3D
- java - java中将JSON数组字符串转换为列表的通用方法
- amazon-web-services - 用于 prod 的 k8s 高可用性配置边缘案例
- r - r:在特定条件下将日期添加到日期变量
- javascript - 你如何只映射索引的一部分?反应
- python - 如何在python中构建一个函数来解决:如果X公司的标签一年一次从0变为1,那么我们返回1,否则返回0?