简体   繁体   English

在Pandas 0.21.0版之后,如何将Python dict转换为DataFrame列?

[英]How to convert Python dict to DataFrame columns after Pandas version 0.21.0?

I am trying to run the same script over two computers, and have my dict structure, data, convert to Pandas DataFrame. 我试图在两台计算机上运行相同的脚本,并让我的字典结构,数据转换为Pandas DataFrame。

df = pd.DataFrame(data, columns=[column_label])
df.to_csv('./result.csv', mode='w', index=False)

It works perfectly on the computer with Pandas version less than 0.21.0. 它在Pandas版本小于0.21.0的计算机上完美运行。 However, when I execute the same code over to my server, suddenly it would generate a csv file with just the column labels, and none of the data. 但是,当我在服务器上执行相同的代码时,突然会生成仅带有列标签而没有任何数据的csv文件。

I tried to print out the values of df, and on the server it's all NAN. 我试图打印出df的值,并且在服务器上全部为NAN。

When I remove the columns part like this: 当我像这样删除列部分时:

df = pd.DataFrame(data)
df.to_csv('./result.csv', mode='w', index=False)

Suddenly the data are back, albeit the columns are missing and the data are not in order. 突然,数据又回来了,尽管缺少列并且数据不整齐。

If I do 如果我做

df = pd.DataFrame(data)
df.columns = column_label
df.to_csv('./result.csv', mode='w', index=False)

The column labels are back, but the column labels are out of order, and the data is also doesn't match the order of the column labels. 列标签向后,但列标签顺序不正确,并且数据也与列标签的顺序不匹配。

If I do 如果我做

df = pd.DataFrame(columns=[column_label])
df = pd.DataFrame(data)
df.to_csv('./result.csv', mode='w', index=False)

The the data matches the order of the column labels, but the column labels themselves are out of order... 数据与列标签的顺序匹配,但是列标签本身不正确...

I have since upgrade my pandas library on the computer that was working from 0.17.0 to 0.22.0, and it has also stopped working. 此后,我已将运行0.10.1的计算机上的pandas库升级到0.22.0,并且它也停止了工作。

So for some reason, assigning data and columns=[column_label] to a DataFrame in one line seems to break the dict to DataFrame conversion after Pandas version 0.21.0. 因此,出于某种原因,在Pandas 0.21.0版之后,将数据和column = [column_label]分配给DataFrame的一行似乎打破了将数据转换为DataFrame的命令。

How should I do columns assignment with the newer versions of Pandas? 如何使用较新版本的Pandas进行列分配?

I am assuming column_label is a list.The columns parameter of pandas just requires a list of column names. 我假设column_label是一个列表.pandas的columns参数只需要一个列名列表。 What you are doing by passing [column_label] to the columns parameter is passing a list of lists. 通过将[column_label]传递给columns参数,您正在执行的是传递列表列表。 Try without [] . 尝试不使用[]

df = pd.DataFrame(data, columns=column_label)

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

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