[英]Pandas df split values out from one column into their own columns
我該如何使用Pandas和Python? 我正在使用Jupyter Notebook。
我有一個這樣的數據框:
col
0 2017 / something
1 $5.91 (× 1)
2 Premium
3 2017 / anotherthing
4 $16.0 (× 1)
5 Business
我想從那里將值拆分成自己的列,如下所示:
col revenue plan
0 2017 / something $5.91 (× 1) Premium
1 2017 / anotherthing $16.0 (× 1) Business
然后從收入列中刪除括號值和美元符號,因此我得出以下結論:
col revenue plan
0 2017 / something 5.91 Premium
1 2017 / anotherthing 16.0 Business
In [113]: (df[['col']].replace(r'\s*\([^\)]*\)', '', regex=True)
...: .set_index(np.arange(len(df))//3)
...: .set_index(np.arange(len(df))%3, append=True)['col']
...: .unstack())
...:
Out[113]:
0 1 2
0 2017 / something $5.91 Premium
1 2017 / anotherthing $16.0 Business
使用pd.MultiIndex.from_arrays
和__divmod__
我們使用3
的值,因為我們想要結果3列。
d = df.set_index(
pd.MultiIndex.from_arrays(np.arange(len(df)).__divmod__(3))
).col.unstack().rename(columns={0: 'col', 1: 'revenue', 2: 'plan'})
d.assign(revenue=d.revenue.str.extract('\$(.*) \(', expand=False))
col revenue plan
0 2017 / something 5.91 Premium
1 2017 / anotherthing 16.0 Business
修改了其他部分解決方案,以結合使用更清潔的解決方案來獲得op的請求輸出。
# make dataframe
df = pd.DataFrame(columns=['col'], data=['2017 / something', '$5.91 (× 1)', 'Premium', '2017 / anotherthing', '$16.0 (× 1)', 'Business'])
# break into 3 columns(per piRSquared's solution) and rename
df = df.set_index(
pd.MultiIndex.from_arrays(np.arange(len(df)).__divmod__(3))
).col.unstack().rename(columns={0: 'col', 1: 'revenue', 2: 'plan'})
# strip parenthesis values and dollar signs
df.revenue = df.revenue.replace(r'\s*\([^\)]*\)', '', regex=True).str.strip('$')
print(df)
輸出:
col revenue plan
0 2017 / something 5.91 Premium
1 2017 / anotherthing 16.0 Business
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.