2016-09-18 64 views
0

我试图在大熊猫建立一个2×24表与下面的以下数据:提取数据,并创建新的表

d.iloc[0:2] = [[0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L], [0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 2L, 2L, 0L, 0L, 0L]] 

基本上,在第一子托架表示24小时一月的一天数据和二月的第二个小括号。 我期待结构2X24表(没有“L”)以下列方式:

1 2 3 4 5 6 7 8 9 10 11 12 ... 24 
Jan 0 0 0 0 0 0 0 0 0 1 1 1 ... 0 
Feb 0 0 0 0 0 0 0 0 0 1 1 1 ... 0 

我发现了什么挑战性的剥离(.strip),分割,并将数据复制到一个新的数据帧结构。我经常在网上的数据框中找到12个子括号(每月一个)的原始结构。 我包含d.iloc[0,2],因为我打算使用for循环将函数应用于第2列中的所有元素。 谢谢你宝贵的帮助。

回答

1

我认为你可以使用DataFrame.from_records与应用str.strip:由dt.strftime有个名字产生

import pandas as pd 
import numpy as np 

a = [['0L', '0L', '0L', '0L', '0L', '0L', '0L', '0L', '0L', '1L', '1L', '1L', '1L', '1L', '0L', '0L', '0L', '1L', '1L', '1L', '1L', '0L', '0L', '0L'], 
    ['0L', '0L', '0L', '0L', '0L', '0L', '0L', '0L', '0L', '1L', '1L', '1L', '1L', '1L', '0L', '0L', '0L', '1L', '1L', '2L', '2L', '0L', '0L', '0L']] 

idx = ['Jan','Feb'] 
df = pd.DataFrame.from_records(a, index=idx).apply(lambda x: x.str.strip('L').astype(int)) 
print (df) 
    0 1 2 3 4 5 6 7 8 9 ... 14 15 16 17 18 19 20 \ 
Jan 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 1 1 
Feb 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 2 2 

    21 22 23 
Jan 0 0 0 
Feb 0 0 0 

[2 rows x 24 columns] 

更通用的解决方案:

print (pd.Series(range(1,len(a) + 1))) 
0 1 
1 2 
dtype: int32 

idx = pd.to_datetime(pd.Series(range(1,len(a) + 1)), format='%m').dt.strftime('%b') 
0 Jan 
1 Feb 
dtype: object 

df = pd.DataFrame.from_records(a, index=idx).apply(lambda x: x.str.strip('L').astype(int)) 
print (df) 
    0 1 2 3 4 5 6 7 8 9 ... 14 15 16 17 18 19 20 \ 
Jan 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 1 1 
Feb 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 2 2 

    21 22 23 
Jan 0 0 0 
Feb 0 0 0 

如果需要split值第一:

b = [['0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L'], 
    ['0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 2L, 2L, 0L, 0L, 0L']] 

idx = pd.to_datetime(pd.Series(range(1,len(a) + 1)), format='%m').dt.strftime('%b') 

df1 = pd.DataFrame.from_records(b, index=idx) 
     .iloc[:,0] 
     .str.split(', ', expand=True) 
     .replace({'L':''}, regex=True) 
     .astype(int) 
print (df1) 

    0 1 2 3 4 5 6 7 8 9 ... 14 15 16 17 18 19 20 \ 
Jan 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 1 1 
Feb 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 2 2 

    21 22 23 
Jan 0 0 0 
Feb 0 0 0 

[2 rows x 24 columns] 
+0

它是如何工作的? – jezrael

+0

谢谢你的详细解答。我不能将.str.strip('L')。astype(int)应用于数据框的单元格:AttributeError:'str'对象没有属性'str'。怎么来的? (单元格是str类型) – John12

+0

它不能与样本或实际数据一起使用? – jezrael

相关问题