[英]I have dictionary as value in pandas dataframe columns. I want to make the keys columns and values as column value
So i'm working on a dataframe which has a key-value pair as its value in columns.所以我正在研究一个 dataframe ,它有一个键值对作为列中的值。 Is there a way to make the keys as column name while only keeping the value left in the column.有没有办法将键作为列名,同时只保留列中的值。
Currently i have something like this:目前我有这样的事情:
>0 1 2
>{'1536235175000': 26307.9} {'1536235176000': 0} {'1536236701000': 2630}
>{'1536239919000': 1028127} {'1536239921000': 0} NaN
>{'1536242709000': 2629.6} {'1536242711000': 0} NaN
If you want to keep the row index, you can agg every row as as list and explode them.如果要保留行索引,可以将每一行聚合为列表并展开它们。
obj = df.apply(lambda x: list(x), axis=1).explode().dropna()
dfn = pd.DataFrame(obj.tolist(), index=obj.index)
dfn.stack().unstack()
# 1536235175000 1536235176000 1536236701000 1536239919000 \
# 0 26307.9 0.0 2630.0 NaN
# 1 NaN NaN NaN 1028127.0
# 2 NaN NaN NaN NaN
# 1536239921000 1536242709000 1536242711000
# 0 NaN NaN NaN
# 1 0.0 NaN NaN
# 2 NaN 2629.6 0.0
Check with concat
用concat
检查
pd.concat([pd.Series(df[x].tolist()) for x in df.columns], keys=df.columns, axis=1)
If lakes is your DataFrame, you can do something like如果湖泊是您的 DataFrame,您可以执行类似的操作
area_dict = dict(zip(lakes.area, lakes.count)
) area_dict = dict(zip(lakes.area, lakes.count)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.