【问题标题】:Reading Vertically arranged data from .csv file using pandas使用 pandas 从 .csv 文件中读取垂直排列的数据
【发布时间】:2020-10-10 08:30:55
【问题描述】:

我有一个 .csv,如下图所示:

我想创建 4 个数据框,我目前正在使用 .iloc 进行创建

import pandas as pd
enter code here
file_path='/file/path/name.csv'
df_main=pd.read_csv(file_path)
enter code here
df_global=df_main.iloc[:3,:]
df_mkt_a=df_main.iloc[6:9,:]
df_mkt_b=df_main.iloc[12:15,:]
df_mkt_c=df_main.iloc[18:21,:]

但这可能会在添加/删除行时遇到问题,并且非常不灵活。

还有什么更 Pythonic 的方式来读取这些数据?

【问题讨论】:

    标签: python pandas csv


    【解决方案1】:

    这会生成一个数据帧列表,利用文件中数据补丁之间的空白行将评估为 nan 的事实

    df = pd.read_csv('test.csv', header =None)
    
    # split at rows that have all nan entries
    splits = [0] + [ix for ix in df[df.isnull().all(axis=1)].index] + [len(df)]
    dfs = [df[splits[i]:splits[i+1]] for i in range(len(splits)-1)]
    

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 2021-07-03
      相关资源
      最近更新 更多