字典中的 pandas 数据框具有空列表值 [英] Pandas Dataframe from dict with empty list value
问题描述
我正在尝试用两个键读字典,第一个键是字符串值,第二个键是字符串值列表.包含列表的值可以为(通常为空).例如:
I am trying to read in a dictionary with two keys, the first with a string value and the second with a list of string values. The value containing a list can be (and often is) empty. For example:
{'number': '50', 'box': []}
但是,当我尝试使用DataFrame.from_dict
时,它给了我一个空的DataFrame.我注意到,如果框"列表包含多个元素,则DataFrame.from_dict
将为我提供一个包含多行的DataFrame,框列表中的每个值对应一个.这似乎是一种副产品行为.有没有一种方法可以抑制这种行为,以便我可以从上面的示例生成一个带有一行的数据帧,其中数字"列的值为"50",而框"列的值为[]
?
However, when I try to use DataFrame.from_dict
, it gives me an empty DataFrame. I notice that if the 'box' list has multiple elements, DataFrame.from_dict
will give me a DataFrame with multiple rows, one for each value in the box list. This appears to be a sort of crossproduct behavior. Is there a way for me to suppress this behavior so that I can generate a DataFrame from the above example with one row, where the column "number" has value '50' and column "box" has value []
?
我正在通过Anaconda 2.3.0(64位Windows)使用Pandas 0.16.2和Python 2.7.10.
I am using Pandas 0.16.2 and Python 2.7.10 via Anaconda 2.3.0 (64-bit Windows).
推荐答案
如果要使DataFrame具有单个行,则可以提供带有单个字典的列表:
If you want to make a DataFrame with a single row, you can provide a list with a single dictionary:
df = pd.DataFrame([{'number': '50', 'box': []}])
from_dict
函数期望列表字典,其中键代表列,每个值是一个列表(因为DataFrame通常具有多于一行),代表每一行的值.以下使用from_dict
产生等效的结果:
df = pd.DataFrame.from_dict({'number': ['50'], 'box': [[]]})
这篇关于字典中的 pandas 数据框具有空列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!