How to iterate over a DataFrame and create a new DataFrame

My data frame looks like this:

P Q L
1 2 3
2 3 
4 5 6,7

The goal is to check if there is any value in L, if so, extract the value in the columns Land P:

P L
1 3
4,6
4,7

Please note that there Lmay be several values, in the case of more than 1 value I will need two lines.

Below is my script, it cannot give the expected result.

df2 = []
ego
other
newrow = []

for item in data_DF.iterrows():
    if item[1]["L"] is not None:
        ego = item[1]['P']
        other = item[1]['L']
        newrow = ego + other + "\n"
        df2.append(newrow)

data_DF2 = pd.DataFrame(df2)
+4
source share
2 answers

L dataframe s . L Q. df NaN .

print df
   P  Q    L
0  1  2    3
1  2  3  NaN
2  4  5  6,7

s = df['L'].str.split(',').apply(pd.Series, 1).stack()
s.index = s.index.droplevel(-1) # to line up with df index
s.name = 'L'
print s
0    3
2    6
2    7
Name: L, dtype: object

df = df.drop( ['L', 'Q'], axis=1)
df = df.join(s)
print df
   P    L
0  1    3
1  2  NaN
2  4    6
2  4    7
df = df.dropna().reset_index(drop=True)
print df
   P  L
0  1  3
1  4  6
2  4  7
0

-, L P, L :

df2 = df[~pd.isnull(df.L)].loc[:, ['P', 'L']].set_index('P')

L :

df2 = df2.L.str.split(',', expand=True).stack()
df2 = df2.reset_index().drop('level_1', axis=1).rename(columns={0: 'L'}).dropna()
df2.L = df2.L.str.strip()

: P index string L ',' . .

+1

Source: https://habr.com/ru/post/1618416/


All Articles