Pandas没有附加datafram

2024-10-04 03:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试,但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

Tags: dataframedf列表title空白形式listpd
2条回答

你差点就搞定了。只要改变你构造数据帧的方式

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

印刷品:

^{pr2}$

您需要将DataFrames追加到列表dfs中,然后将^{}与参数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

^{pr2}$

但我认为最好是使用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"]
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

相关问题 更多 >