For example I have this dataframe :
X Y
ABCDEFGH 220105
ABCDEFGH 22H1 4
and I want to do this
for name in df['X']:
set1=name
set2=the 6th char of Y
set3=all numbers before 6th without space
so, I have tried
for name in df['X']:
set1=name
set2=df.loc[df['X']==name, 'Y'].str[5]
set3=df.loc[df['X']==name, 'Y'].str[0:4]
Does not work because I have 2 same X values 'ABCDEFGH', so at set2 and set 3 the result is list. Meanwhile what I want is to have 2set1, 2set2, 2set 3 i.e
set1=ABCDEFGH
set2=5
set3=22010
set1=ABCDEFGH
set2=4
set3=22H1
CodePudding user response:
You can try:
for idx, row in df.iterrows():
set1 = row['X']
set2 = row['Y'][5]
set3 = row['Y'].split()[0][:5]
Output if you had prints:
set1='ABCDEFGH'
set2='5'
set3='22010'
set1='ABCDEFGH'
set2='4'
set3='22H1'
CodePudding user response:
Use from this code
df.reset_index(drop=True, inplace=True)
for i in df.index:
set1=df.at[i, 'X']
set2=df.at[i, 'Y'][5]
set3=df.at[i, 'Y'][0:4]
Output is
set1='ABCDEFGH'
set2='5'
set3='22010'
set1='ABCDEFGH'
set2='4'
set3='22H1'