You can do:
df["Shape"]=df["Shape"].str.split("\r\n")
print(df.explode("Shape").reset_index(drop=True))
Output:
Color Shape Price
0 Green Rectangle 10
1 Green Triangle 10
2 Green Octangle 10
3 Blue Rectangle 15
4 Blue Triangle 15
Answer from Sociopath on Stack OverflowYou can do:
df["Shape"]=df["Shape"].str.split("\r\n")
print(df.explode("Shape").reset_index(drop=True))
Output:
Color Shape Price
0 Green Rectangle 10
1 Green Triangle 10
2 Green Octangle 10
3 Blue Rectangle 15
4 Blue Triangle 15
This might not be the most efficient way to do it but I can confirm that it works with the sample df:
data = [['Green', 'Rectangle\r\nTriangle\r\nOctangle', 10], ['Blue', 'Rectangle\r\nTriangle', 15]]
df = pd.DataFrame(data, columns = ['Color', 'Shape', 'Price'])
new_df = pd.DataFrame(columns = ['Color', 'Shape', 'Price'])
for index, row in df.iterrows():
split = row['Shape'].split('\r\n')
for shape in split:
new_df = new_df.append(pd.DataFrame({'Color':[row['Color']], 'Shape':[shape], 'Price':[row['Price']]}))
new_df = new_df.reset_index(drop=True)
print(new_df)
Output:
Color Price Shape
0 Green 10 Rectangle
1 Green 10 Triangle
2 Green 10 Octangle
3 Blue 15 Rectangle
4 Blue 15 Triangle
Pandas to split single df row into multiple
Split the pandas dataframe by a column value
ENH: Add split method to DataFrame for flexible row-based partitioning
python - Pandas Split DataFrame using row index - Stack Overflow
Hi there. I'm trying to rack my brain about how to accomplish this. I have a form where each submission is one row in a csv file.
| ID | Name1 | Age | Name2 | Age |
|---|---|---|---|---|
| 001 | Joe | 25 | Mary | 89 |
| 002 | Chris | 38 |
What I want to accomplish is to splice a single row into 2 rows if Name2 has a value. I want to take this original df, and create something like this:
| ID | Name | Age |
|---|---|---|
| 001 | Joe | 25 |
| 001 | Mary | 89 |
| 002 | Chris | 38 |
That way, I can still group submissions (it's easy to see that Joe and Mary came from the same form), but I have a clean df.
df2=pd.DataFrame(columns=['ID','Name','Age])
#append just the first 3 columns 0,1,2 to new df2
for x in range(len(df):
df2.append(df[x,0:3]
#append columns 0,3,4 to df2--but only if there is data in the Name2 column
if pd.notnull(df.iloc[x,3]):
df2.append(df.iloc[x,0]
df2.append(df.iloc[x,3:5]This is my logic, but not implementing correctly. Can somebody point me to the right direction? Is this a smart way to approach this? In reality, I have a csv file with about 100 columns and I'm picking and choosing new columns to be added to a much cleaner second data frame. This involves lots of guessing about which columns I want and then getting the right index for .iloc.
Thanks for any tips.
You could use list comprehension with a little modications your list, l, first.
print(df)
a b c
0 1 1 1
1 2 2 2
2 3 3 3
3 4 4 4
4 5 5 5
5 6 6 6
6 7 7 7
7 8 8 8
l = [2,5,7]
l_mod = [0] + l + [max(l)+1]
list_of_dfs = [df.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]
Output:
list_of_dfs[0]
a b c
0 1 1 1
1 2 2 2
list_of_dfs[1]
a b c
2 3 3 3
3 4 4 4
4 5 5 5
list_of_dfs[2]
a b c
5 6 6 6
6 7 7 7
list_of_dfs[3]
a b c
7 8 8 8
I think this is what you need:
df = pd.DataFrame({'a': np.arange(1, 8),
'b': np.arange(1, 8),
'c': np.arange(1, 8)})
df.head()
a b c
0 1 1 1
1 2 2 2
2 3 3 3
3 4 4 4
4 5 5 5
5 6 6 6
6 7 7 7
last_check = 0
dfs = []
for ind in [2, 5, 7]:
dfs.append(df.loc[last_check:ind-1])
last_check = ind
Although list comprehension are much more efficient than a for loop, the last_check is necessary if you don't have a pattern in your list of indices.
dfs[0]
a b c
0 1 1 1
1 2 2 2
dfs[2]
a b c
5 6 6 6
6 7 7 7