【发布时间】:2021-10-31 15:28:46
【问题描述】:
【问题讨论】:
-
总是有助于以可重现的形式共享样本数据;你可以做一个
df.to_dict('records'),将数据作为字典共享
标签: pandas multi-index cartesian-product
【问题讨论】:
df.to_dict('records'),将数据作为字典共享
标签: pandas multi-index cartesian-product
这是我使用pandas.MultiIndex 解决的方法:
import pandas as pd
from io import StringIO
# Create sample data
data = 'A,B,C,D,E\nw2,a,xx,r1,50\nw4,b,mx,r2,51\nw8,c,,r5,52\n,d,,,53\n'
# Read sample for this we need to use read_csv with StrigIO as input
df = pd.read_csv(StringIO(data))
# Use MultiIndex
# To get the expected result drop na values
idx = pd.MultiIndex.from_product([df[x].dropna().values for x in df.columns],names=df.columns)
# Create new dataframe using the multi-index
dfn = idx.to_frame(index=False)
print(dfn)
【讨论】:
idx.to_frame(0)而不是创建一个新的df并重置它的索引。