简体   繁体   English

如何从同一数据框中的字典键创建具有键名的列?

[英]How can I create column having key name from dictionary keys in same dataframe?

I have a dataframe, something like:我有一个数据框,例如:

|   | a | b                |
|---|---|------------------|
| 0 | a | {'d': 1, 'e': 2} |
| 1 | b | {'d': 3, 'e': 4} |
| 2 | c | NaN              |
| 3 | d | {'f': 5}         |

I am using the following code from df.join(pd.DataFrame.from_records(df['b'].mask(df.b.isna(), {}).tolist())) How can I create column from dictionary keys in same dataframe?我正在使用df.join(pd.DataFrame.from_records(df['b'].mask(df.b.isna(), {}).tolist()))的以下代码如何从字典创建列同一个数据框中的键? and getting result like:并得到如下结果:

|   | a | b                | d | e | f |
|---|---|------------------|---|---|---|
| 0 | a | {'d': 1, 'e': 2} | 1 | 2 |nan|
| 1 | b | {'d': 3, 'e': 4} | 3 | 4 |nan|
| 2 | c | NaN              |nan|nan|nan|
| 3 | d | {'f': 5}         |nan|nan| 5 |

How can make something like this:如何制作这样的东西:

|   | a | b                | b_d | b_e | b_f |
|---|---|------------------|---  |---  |---  |
| 0 | a | {'d': 1, 'e': 2} |  1  |  2  | nan |
| 1 | b | {'d': 3, 'e': 4} |  3  |  4  | nan |
| 2 | c | NaN              | nan | nan | nan |
| 3 | d | {'f': 5}         | nan | nan |  5  |

使用DataFrame.add_prefix

df.join(pd.DataFrame.from_records(df['b'].mask(df.b.isna(), {}).tolist()).add_prefix('b_'))

暂无
暂无

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

相关问题 如何从同一个 dataframe 中的字典键创建列? - How can I create column from dictionary keys in same dataframe? 如何创建字典外的列表,其名称与字典键相同,并且大小与该键的值相同? - How do I create lists out of dictionary, having same name as dictionary keys and same size as value of that key? 如何将 pandas dataframe 中的列值作为新的键值对添加到具有字典的另一列中? - How can I add column values from a pandas dataframe as a new key value pair in another column having dictionary? 如何创建密钥字典:column_name和value:python中来自数据框的列中的唯一值 - How to create a dictionary of key : column_name and value : unique values in column in python from a dataframe 如何为列表中的一个键创建具有多个值的 Python 字典,然后创建具有一列和多行的 pandas 数据框 - How can I create a Python dictionary with multiple values for one key from a list, to then create a pandas dataframe with one column and multiple rows 如何使用字典中的键作为索引创建 pandas DataFrame? [蟒蛇,熊猫] - How can I create a pandas DataFrame with keys from a dictionary as my index? [Python, pandas] 如何从每个键的键列表中初始化 python 中的字典以具有相同的初始值? - How can I initialize a dictionary in python from a list of keys for each key to have the same initial value? Python如何从字典中获取所有值相同的名称键 - Python How can I get all values same name keys from dictionary 如何创建嵌套字典键并从命名空间键值对列表中为其分配值? - how can I create nested dictionary keys and assign them values from a list of namespaced key value pairs? 如何将字典键作为 dataframe 的列? - How can I make dictionary key as column of dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM