使用Pandas将数据框内的变量拆分为行 [英] Splitting variables within dataframe into rows using pandas
问题描述
我在这里看到过类似的问题,但似乎无法为我的数据获得正确的输出.我有一个看起来像这样的熊猫数据框:
I've seen similar questions asked here, but I can't seem to get the right output for my data. I have a pandas dataframe that looks like this:
pm_code sec_pm site_no state
0 010_628 010_228 015_634 2543677 2543677 2543677 010228955 me
我想将每个单元格分成多行(按空格分割),并按state和site_no进行索引.
I'd like to break each cell into multiple rows (split by space) and indexed by state and site_no.
感谢您的帮助!
推荐答案
使用str.split
拆分前两列并提取其值.
Split the first two columns using str.split
and extract its values.
x = df.iloc[:, :2].applymap(str.split).values.tolist()[0]
x = list(zip(*x))
现在,获取最后两列并对其进行扩展以匹配拆分后前两列的值.
Now, take the last two columns and extend them to match the values of the first two columns post split.
y = np.repeat(df.iloc[:, -2:].values[:, ::-1], len(x), axis=0)
现在,创建您的数据框.
Now, create your dataframe.
df2 = pd.DataFrame(x, index=y, columns=df.columns[:2])
df2
pm_code sec_pm
(me, 10228955) 010_628 2543677
(me, 10228955) 010_228 2543677
(me, 10228955) 015_634 2543677
如果要使用MultiIndex
,则需要致电pd.MultiIndex
:
If you want a MultiIndex
instead, you'd need to call pd.MultiIndex
:
# https://stackoverflow.com/a/45946551/4909087
df2 = pd.DataFrame(x, index=pd.MultiIndex.from_arrays(y.T), columns=df.columns[:2])
df2
pm_code sec_pm
me 10228955 010_628 2543677
10228955 010_228 2543677
10228955 015_634 2543677
这篇关于使用Pandas将数据框内的变量拆分为行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!