I have the data in dataframes like below. I want to split the item into same number of rows
>>> df
idx a
0 3
1 5
2 4
from above dataframe, I want the below as
>>> df
idx a
0 1
1 2
2 3
3 1
4 2
5 3
6 4
7 5
8 1
9 2
10 3
11 4
I tried several ways, but no success.
to call apply with a lambda function that calls str.split to split the x string value. And then we call explode to fill new rows with the split values. Finally, we call `reset_index to reset the index numbers after filling the rows with the split values. To split cell into multiple rows in a Python Pandas dataframe, we can use the apply method.
The dataframe iloc () function is used to slice the dataframe and select entries based on the index range of rows and columns. If a colon (:) is passed as an index range for rows and columns then all entries of corresponding rows and columns data will be included in the dataframe output. 4. Pandas Split dataframe by list of indexes
Pandas <code>str.split () strategy can be applied to an entire arrangement. .str must be prefixed every time before calling this strategy to separate it from the Python’s default work; else, it will toss a mistake. Pat refers to string worth, separator, or delimiter to isolate string at.
First, convert each string of names to a list. Now, split names column list values (columns with individual list values are created). Merge the new columns with the rest of the data set. Drop the old names list column and then transform the new columns into separate rows using the melt function.
A Fun way
df.a.map(range).explode()+1 # may add reset_index(), however, I think keep the original index is good, and help us convert back.
Out[158]:
idx
0 1
0 2
0 3
1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
2 4
Name: a, dtype: object
Here is a way with series.repeat
+Groupby. cumcount
assuming idx
is the index- if not df.set_index('idx')['a']..rest of the code..
(df['a'].repeat(df['a']).groupby(level=0).cumcount().add(1)
.reset_index(drop=True).rename_axis('idx'))
idx
0 1
1 2
2 3
3 1
4 2
5 3
6 4
7 5
8 1
9 2
10 3
11 4
dtype: int64
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With