I want to iterate specific rows based on the number of the list factors in 'Content ID_group' column. For example, as the first row of the table under has 6 factors in its list in 'Content ID_group' column, I want to make other columns(Event Name, Media) iterate 6 times.
So if the original graph is like this:
Event Name | Media | Content ID_group |
---|---|---|
ord | [1,2,3,4,5,6] | |
inflow | appier | 0 |
The final graph will look like this:
Event Name | Media | Content ID_group |
---|---|---|
ord | 1 | |
ord | 2 | |
ord | 3 | |
ord | 4 | |
ord | 5 | |
ord | 6 | |
inflow | appier | 0 |
So this is my code. It just keeps running, not giving out the result. So I guess it is an infinite loop.
Can someone help?
*'graph' is the graph I defined. **'g_whole' is the dataframe that has to contain all the iteration result that I defined.
g_whole=pd.DataFrame()
for g in range(len(graph)):
if type(graph['Content ID_group'][0]) == list:
loop=len(graph['Content ID_group'][0])
for l in range(loop):
itt=graph.loc[g]
g_whole.append(itt)
elif type(graph['Content ID_group'][0]) == int:
g_whole.append(graph['Content ID_group'][0])
print(g_whole)
CodePudding user response:
Assuming Content ID_group
contains a real list, you can use explode
:
>>> type(graph.at[0, 'Content ID_group'])
list
>>> graph.explode('Content ID_group')
Event Name Media Content ID_group
0 ord google 1
0 ord google 2
0 ord google 3
0 ord google 4
0 ord google 5
0 ord google 6
1 inflow appier 0
If Contains ID_group
contains strings, you have to eval
first:
>>> type(graph.at[0, 'Content ID_group'])
str
>>> graph['Content ID_group'] = graph['Content ID_group'].apply(pd.eval)
>>> graph.explode('Content ID_group')
Event Name Media Content ID_group
0 ord google 1
0 ord google 2
0 ord google 3
0 ord google 4
0 ord google 5
0 ord google 6
1 inflow appier 0
CodePudding user response:
Just use pd.DataFrame.explode
:
>>> df.explode('Content ID_group')
Event Name Media Content ID_group
0 ord google 1
0 ord google 2
0 ord google 3
0 ord google 4
0 ord google 5
0 ord google 6
1 inflow appier 0
>>>
CodePudding user response:
In [1]: df = pd.DataFrame({'Event Name': ['ord', 'inflow'], 'Media': ['google', 'appier'], 'Content ID_group': [[1,2,3,4,5,6], 0]})
In [2]: df.explode('Content ID_group')
Out[2]:
Event Name Media Content ID_group
0 ord google 1
0 ord google 2
0 ord google 3
0 ord google 4
0 ord google 5
0 ord google 6
1 inflow appier 0
CodePudding user response:
import pandas as pd
df = pd.DataFrame({"Event Name": ["ord", "inflow"], "Media":["google", "appier"], "Content Id_group":[[1,2,3,4,5,6], 0]})
print(df)
Event Name Media Content Id_group
0 ord google [1, 2, 3, 4, 5, 6]
1 inflow appier 0
df2 = df.explode("Content Id_group")
print(df2)
Event Name Media Content Id_group
0 ord google 1
0 ord google 2
0 ord google 3
0 ord google 4
0 ord google 5
0 ord google 6
1 inflow appier 0