简体   繁体   English

pandas dataframe from_dict - 为键设置列名,为键值设置列名

[英]pandas dataframe from_dict - Set column name for key, and column name for key-value

I have a dictionary as follows:我有一本字典如下:

my_keys = {'a':10, 'b':3, 'c':23}

I turn it into a Dataframe:我把它变成了一个数据框:

df = pd.DataFrame.from_dict(my_keys)

It outputs the df as below它输出df如下

     a     b    c
0    10    3    23

How can I get it to look like below:我怎样才能让它看起来像下面这样:

Col1    Col2
a        10
b         3
c        23

I've tried orient=index but I still can't get column names?我试过 orient=index 但我仍然无法获得列名?

You can create list of tuples and pass to DataFrame constructor:您可以创建元组列表并传递给DataFrame构造函数:

df = pd.DataFrame(list(my_keys.items()), columns=['col1','col2'])

Or convert keys and values to separate lists:或者将键和值转换为单独的列表:

df = pd.DataFrame({'col1': list(my_keys.keys()),'col2':list(my_keys.values())})

print (df)
  col1  col2
0    a    10
1    b     3
2    c    23

Your solution should be changed by orient='index' and columns , but then is necessary add DataFrame.rename_axis and DataFrame.reset_index for column from index :您的解决方案应该由orient='index'columns ,但是有必要为来自index列添加DataFrame.rename_axisDataFrame.reset_index

df = (pd.DataFrame.from_dict(my_keys, orient='index', columns=['col2'])
        .rename_axis('col1')
        .reset_index())

暂无
暂无

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

相关问题 如果dict键中的A列为值,则将B列设置为pandas数据框中的dict值 - If column A value in dict key, set column B to dict value in pandas dataframe 在 A 列中搜索 dict 键的文本,如果找到,则将 B 列设置为 Pandas dataframe 中的 dict 值 - Search text in column A for dict key, if found then set column B to dict value in Pandas dataframe 有效地将 pandas dataframe 列的组合转换为键值对 - Efficiently converting combination of pandas dataframe column into key-value pair 将 dataframe 转换为 dict,使用列名作为键,另一列作为 k,v - python,pandas,Z6A55074B5CDF47549 - convert dataframe to dict, using a column name as key and another columns as k, v - python, pandas, dataframe 使用 orient = 'index' 在 Pandas 数据框 from_dict 中设置列​​名 - Set column names in pandas data frame from_dict with orient = 'index' 将dict转换为pandas dataframe,键为column1,值为col2 - Convert dict to pandas dataframe with key as column1 and value as col2 带有嵌套字典的列表中的数据帧,其中第一个字典的键是列和键,第二个字典的值是行和值 - DataFrame from list with nested dicts where key of first dict is column and key, value of second dict is row and value 如何将 append Python 字典到 Pandas ZBA834BA059A9A379459C112175EB88E 匹配到列名键 - How to append Python dictionary to Pandas DataFrame, matching the key to the column name 为从dict创建的pandas数据框设置一个名称 - set a name for pandas dataframe that created from dict 基于pandas DataFrame Key Column的动态文件名 - Dynamic File Name based on pandas DataFrame Key Column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM