在Pandas中将行拆分为多列 [英] Splitting rows into multiple columns in Pandas
本文介绍了在Pandas中将行拆分为多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有这个数据框:
df = pd.DataFrame(['Function_1','internal_prop_1','external_prop_1','Function_2','internal_prop_2','external_prop_2','Function_3','internal_prop_3','external_prop_3'], columns=['Raw_info'])
Raw_info
0 Function_1
1 internal_prop_1
2 external_prop_1
3 Function_2
4 internal_prop_2
5 external_prop_2
6 Function_3
7 internal_prop_3
8 external_prop_3
我基本上想创建一个具有以下格式的新数据框
I basically want to create a new dataframe with the following formate
Function_name prop1 prop2
0 Function_1 internal_prop_1 external_prop_1
1 Function_2 internal_prop_2 external_prop_2
2 Function_3 internal_prop_3 external_prop_3
换句话说,我想将三行的每组都分成不同的列。我得到的最接近的是此答案不能解决我的问题。在Pandas中是否有Python或有效的方法来执行此操作,而不是遍历每隔3行并手动进行操作?
In other words, I want to split every set of three rows into different columns. The closest I have got is this answer which does not solve my problem. Is there a Pythonic or efficient way to do this in Pandas, instead of iterating over every alternate 3 rows and doing it manually ?
推荐答案
检索 df.Raw_info.values
,重塑数组并使用 pd.DataFrame
构造函数创建一个新的数据框。
Retrieve df.Raw_info.values
, reshape the array and create a new dataframe with the pd.DataFrame
constructor.
df = pd.DataFrame(df.Raw_info.values.reshape(-1, 3),
columns=['Function_name', 'prop1', 'prop2'])
print(df)
Function_name prop1 prop2
0 Function_1 internal_prop_1 external_prop_1
1 Function_2 internal_prop_2 external_prop_2
2 Function_3 internal_prop_3 external_prop_3
这篇关于在Pandas中将行拆分为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文