![](/img/trans.png)
[英]I have a dataframe with a json substring in 1 of the columns. i want to extract variables and make columns for them
[英]I have dictionary as value in pandas dataframe columns. I want to make the keys columns and values as column value
所以我正在研究一個 dataframe ,它有一個鍵值對作為列中的值。 有沒有辦法將鍵作為列名,同時只保留列中的值。
目前我有這樣的事情:
>0 1 2
>{'1536235175000': 26307.9} {'1536235176000': 0} {'1536236701000': 2630}
>{'1536239919000': 1028127} {'1536239921000': 0} NaN
>{'1536242709000': 2629.6} {'1536242711000': 0} NaN
如果要保留行索引,可以將每一行聚合為列表並展開它們。
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
用concat
檢查
pd.concat([pd.Series(df[x].tolist()) for x in df.columns], keys=df.columns, axis=1)
如果湖泊是您的 DataFrame,您可以執行類似的操作
area_dict = dict(zip(lakes.area, lakes.count)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.