熊猫没有附加数据帧

时间:2016-03-02 12:41:25

标签: python pandas

我正在尝试这个,但是df返回空白 文本框值列表如(54.0,60.18,86.758,73.71) 想想像csv文件的标题是x y h w并且文本框值将附加在其中

import pandas
list111 = [(72.0, 578.18, 378.0, 591.71),(54.0, 564.18, 378.0, 577.71),(54.0, 550.18, 378.0, 563.71),(54.0, 536.18, 378.0, 549.71)]
df = pd.DataFrame()
print df
list_title = ["x","y","h","w"]
for textbox in list111:
    zipped=zip(list_title,textbox)
    df1 = pd.DataFrame(zipped)
    df.append(df1,ignore_index=True)
    print df1,df

2 个答案:

答案 0 :(得分:1)

您需要将DataFrames附加到列表dfs,然后将concat与参数axis=1一起使用:

import pandas as pd
list111 = [ (72.0, 578.18, 378.0, 591.71),
            (54.0, 564.18, 378.0, 577.71),
            (54.0, 550.18, 378.0, 563.71),
            (54.0, 536.18, 378.0, 549.71)]

dfs = []
list_title = ["x","y","h","w"]
for textbox in list111:
    zipped=zip(list_title,textbox)
    df1 = pd.DataFrame(zipped)
    dfs.append(df1)

df = pd.concat(dfs, axis=1, ignore_index=True)
print df
   0       1  2       3  4       5  6       7
0  x   72.00  x   54.00  x   54.00  x   54.00
1  y  578.18  y  564.18  y  550.18  y  536.18
2  h  378.00  h  378.00  h  378.00  h  378.00
3  w  591.71  w  577.71  w  563.71  w  549.71

如果您需要一个公共列index

import pandas as pd

list111 = [ (72.0, 578.18, 378.0, 591.71),
            (54.0, 564.18, 378.0, 577.71),
            (54.0, 550.18, 378.0, 563.71),
            (54.0, 536.18, 378.0, 549.71)]

dfs = []
list_title = ["x","y","h","w"]
for textbox in list111:
    zipped=zip(list_title,textbox)
    df1 = pd.DataFrame(zipped)
    #set first column to index
    df1.set_index(df1.iloc[:,0], inplace =True)
    #append only second column (first is index)
    dfs.append(df1.iloc[:,1])

df = pd.concat(dfs, axis=1, ignore_index=True)
df.index.name = None
print df
        0       1       2       3
x   72.00   54.00   54.00   54.00
y  578.18  564.18  550.18  536.18
h  378.00  378.00  378.00  378.00
w  591.71  577.71  563.71  549.71

但我认为使用DataFrame的{​​{1}}构造函数更好:

import pandas as pd

list111 = [ (72.0, 578.18, 378.0, 591.71),
            (54.0, 564.18, 378.0, 577.71),
            (54.0, 550.18, 378.0, 563.71),
            (54.0, 536.18, 378.0, 549.71)]


list_title = ["x","y","h","w"]
print pd.DataFrame([li for li in list111], columns=list_title).T
        0       1       2       3
x   72.00   54.00   54.00   54.00
y  578.18  564.18  550.18  536.18
h  378.00  378.00  378.00  378.00
w  591.71  577.71  563.71  549.71

答案 1 :(得分:1)

你几乎得到了它。只需更改构建DataFrame的方式

import pandas as pd
list111 = [(72.0, 578.18, 378.0, 591.71),(54.0, 564.18, 378.0, 577.71),(54.0, 550.18, 378.0, 563.71),(54.0, 536.18, 378.0, 549.71)]
list_title = ["x","y","h","w"]

df = pd.DataFrame( data =list111, columns = list_title )
print df

打印:

    x       y    h       w
0  72  578.18  378  591.71
1  54  564.18  378  577.71
2  54  550.18  378  563.71
3  54  536.18  378  549.71