繁体   English   中英

使用 pandas python 将笨拙格式的数据转换为 dataframe

[英]Convert awkwardly formatted data into a dataframe with pandas python

我有以下 csv 格式的一些数据:

变量 1
时间 价值
时间1 12
时间2 32
时间3 4个
时间4 5个
时间5 34
时间6 5个
时间7 46
时间8 7
时间9 8个
时间10 543
变量 2
时间 价值
时间1 1个 2个 3个
时间2 2个 45 5个
时间3 4个 2个 54
时间4 3个 1个 2个
时间5 3个 2个 4个
时间6 4个 5个 8个
时间7 4个 7 4个
时间8 8个 65 12
时间9 12 8个 14
时间10 65 65 13
变量 3
时间 价值
时间1 3个
时间2 4个
时间3 5个
时间4 2个
时间5 1个
时间6 7
时间7 5个
时间8 3个
时间9 5个
时间10 7

并希望将其放入以下数据帧格式中 pandas:

         Variable1    Variable2    Variable3    
Time1           12     [1,2,3]             3
Time2           32    [2,45,5]             4
Time3            4    [4,2,54]             5

我怎么会 go 关于这个? 我知道这种格式很糟糕,不要问我为什么会这样,但我还是坚持了下来。 我真的不知道从哪里开始。 TIA

根据评论更新代码

初始文件读取基于此处的代码:

import pandas as pd
import numpy as np

file = r'C:\Test\TIMBER-1100-10M.csv'
# Loop the data lines
with open(file, 'r') as temp_f:
    # get No of columns in each line
    col_count = [ len(l.split(",")) for l in temp_f.readlines() ]

# Generate column names  (names will be 0, 1, 2, ..., maximum columns - 1)
column_names = [i for i in range(0, max(col_count))]
df = pd.read_csv(file, header=None, delimiter=",", names=column_names)

# preparing dataframe for pivot
df['Variable'] = np.where(df[0].str.contains('VARIABLE:'), df[0], np.nan)
df['Variable'].ffill(inplace=True)
df[1].dropna(inplace=True)
drop_values = ['Timestamp','VARIABLE:']
df2 = df[~df[0].str.contains('|'.join(drop_values))].astype({col: str for col in df.columns[2:]})

conc_col = df2.columns.to_list()
conc_col.remove(0)
conc_col.remove('Variable')

df2['Value'] = df2[conc_col].apply(lambda x: ','.join(x.dropna()), axis=1).str.strip(',nan')
df2.rename(columns={ df.columns[0]: "Time" }, inplace = True)

# creating the pivot as final dataframe
pivot = df2.pivot_table(index=['Time'],
                        columns=['Variable'],
                        values='Value',
                        aggfunc='sum')\
                        .rename_axis(None, axis=1)\
                        .reset_index()
pivot.to_excel(r'C:\Test\temp1.xlsx')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM