简体   繁体   English

从 pandas 空 dataframe 创建一个只有列名的字典

[英]Create a dictionary from pandas empty dataframe with only column names

I have a pandas data frame with only two column names( single row, which can be also considered as headers).I want to make a dictionary out of this with the first column being the value and the second column being the key.I already tried the to.dict() method, but it's not working as it's an empty dataframe.我有一个 pandas 数据框,只有两列名称(单行,也可以视为标题)。我想用它制作一个字典,第一列是值,第二列是键。我已经尝试了to.dict()方法,但它不起作用,因为它是一个空的 dataframe。

Example df=|Land |Norway|示例df=|土地 |挪威| to {'Land': Norway}到{'土地':挪威}

I can change the pandas data frame to some other type and find my way around it, but this question is mostly to learn the best/different/efficient approach for this problem.我可以将 pandas 数据框更改为其他类型并找到解决方法,但这个问题主要是为了学习解决这个问题的最佳/不同/有效方法。

For now I have this as the solution:现在我有这个作为解决方案:

dict(zip(a.iloc[0:0,0:1],a.iloc[0:0,1:2]))

Is there any other way to do this?还有其他方法吗?

Very manual solution非常手动的解决方案

df = pd.DataFrame(columns=['Land', 'Norway'])

df = pd.DataFrame({df.columns[0]: df.columns[1]}, index=[0])

If you have any number of columns and you want each sequential pair to have this transformation, try:如果您有任意数量的列并且您希望每个顺序对都具有此转换,请尝试:

df = pd.DataFrame(dict(zip(df.columns[::2], df.columns[1::2])), index=[0])

Note: You will get an error if your DataFrame does not have at least two columns.注意:如果您的DataFrame没有至少两列,您将收到错误消息。

Here's a simple way convert the columns to a list and a list to a dictionary这是将列转换为列表并将列表转换为字典的简单方法

def list_to_dict(a):
    it = iter(a)
    ret_dict = dict(zip(it, it))
    return ret_dict

df = pd.DataFrame([], columns=['Land', 'Normway'])
dict_val = list_to_dict(df.columns.to_list())
dict_val # {'Land': 'Normway'}

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

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