将数据框Pandas的列更改为其中一列

时间:2018-01-25 18:03:44

标签: python pandas dataframe pivot-table

我有一个看起来像这样的数据表

                              Value      
Code                          ABCD GFHTI
Time                                    
20100101_00:01:33.436-92.451    24  None
20100101_00:01:33.638-92.651  None    25

该表是从日志文件中获取的

logparser = parse_filter_logfile('log.txt')
df = pd.DataFrame(logparser, columns = ['Time', 'Code', 'Value'])
df.set_index(['Time', 'Code']).unstack(-1)

我使用df.pivot(index='Time', columns=['ABCD','GFHTI'])将列更改为ABCD和GFHTI,但我收到以下错误KeyError:'找不到ABCD级别'。

Time                           ABCD GFHTI           
20100101_00:01:33.436-92.451    24  None
20100101_00:01:33.638-92.651  None    25

我想要一个包含列名称的表,看起来像这样:

这有什么工作吗?

这是完整的代码, log.txt的

20100101_00:01:33.436-92.451 BLACKBOX ABCD ref 2183 value 24 
20100101_00:01:33.638-92.651 BLACKBOX GFHTI  ref 2183 value 25 
20100101_00:01:33.817-92.851 BLACKBOX AAAA ref 2183 value 26   
20100101_00:01:34.017-93.051 BLACKBOX BBBB ref 2183 value 27  
  

这个代码:

import pandas as pd
import re

def parse_line(line):
    code_pattern = r'(?<=BLACKBOX )\w+'
    value_pattern = r'(?<=value )\d+'
    code = re.findall(code_pattern, line)[0]
    value = re.findall(value_pattern, line)[0]
    ts = line.split()[0]
    print (type(value))
    return ts, code, value

def parse_filter_logfile(fname):
    with open(fname) as f:
       for line in f:
           data = parse_line(line)
           if data[1] in ['ABCD', 'GFHTI']:
               # only yield rows that match the filter
                print((data))
                yield data

logparser = parse_filter_logfile('log.txt')
df = pd.DataFrame(logparser, columns = ['Time', 'Code', 'Value'])

df.set_index(['Time', 'Code']).unstack(-1)

提前谢谢你。

1 个答案:

答案 0 :(得分:2)

看来你有public class MainActivity extends Activity { AnimationDrawable backgroundAnimation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView backgroundView = (ImageView) findViewById(R.id.backgroundView); backgroundView.setBackgroundResource(R.drawable.animation_bg); backgroundAnimation = (AnimationDrawable) backgroundView.getBackground(); final Button popUpButton = (Button) findViewById(R.id.button); popUpButton.setOnClickListener((view) -> { LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE); View popupView = inflater.inflate(R.layout.activity_pop_up, null); PopupWindow pw = new PopupWindow(popupView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT); pw.showAtLocation(view, Gravity.CENTER, 0, 0); }); } //do something after on create @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); backgroundAnimation.start(); } 列,所以只需使用MultiIndex删除关卡就可以了。

droplevel

df = df.set_index(['Time', 'Code']).unstack(-1)
df.columns = df.columns.droplevel(0)