Pra*_*rma 1 python dictionary dataframe pandas
我有这样的嵌套字典
d = {1 : {'we': 26, 'is': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'pp': 23, 'kj': 74}}
Run Code Online (Sandbox Code Playgroud)
我想将其更改为数据框列,以便外部dict键成为行,其元素作为列的元素.
期望的输出:
rows col1
1 'we': 26, 'is': 112
2 'tp': 26, 'fp': 91
3 'pp': 23, 'kj': 74
Run Code Online (Sandbox Code Playgroud)
如果这是你在字典中的内容,则不一定会保留内部字典的键的顺序.
import pandas as pd
d = {1 : {'we': 26, 'is': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'pp': 23, 'kj': 74}}
# Replace the inner dicts with their string representations
for i in d:
d[i] = str(d[i])
# Convert to dataframe
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
# Clean up column names
df.rename(columns={'index': 'row', 0: 'col1'}, inplace=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6759 次 |
| 最近记录: |