Is there a way to divide it into two using split and for statement and save it as a new data frame?

Asked 2 years ago, Updated 2 years ago, 72 views

Hello. I'm practicing split and For Moon, but there's a blockage.

#1.
for i in range(len(df)) :

    df_split1[i], df_split2[i]=df.loc[i].split(sep='.', maxsplit=1)
#2.
for i in range(len(df)) :

    df.loc[i, 'c']=str(df.loc[i, 'a']).split(sep='.', maxsplit=1)[0]
    df.loc[i, 'd']=str(df.loc[i, 'a']).split(sep='.', maxsplit=1)[1]

Error code : Too many indexers

In the df, in the form of asd.fgh, I'd like to split based on '. in the 'a' column and save the front and back separately. I couldn't go with number 1, so I went with number 2, but there was an error saying "Code" and "Too many indexes"

I want to make a separate DataFrame using split or add a new column from the existing df, but it doesn't work well.

python for split

2022-09-20 15:18

2 Answers

다른 There may be other better ways. Please refer to it only

data = {'a': ['asd.fgh', 'abcd.efg', '123.456']}
df = pd.DataFrame(data=data)

cList = []
dList = []
for idx, row in df.iterrows():
    charList = row['a'].split('.')
    cList.append(charList[0])
    dList.append(charList[1])

df['c'] = pd.DataFrame(cList)
df['d'] = pd.DataFrame(dList)

print(df)

#           #           a     c    d
# # 0   asd.fgh   asd  fgh
# # 1  abcd.efg  abcd  efg
# 2   123.456   123  456

And I looked at the code above later, but it works well I think it's a better way than me. Haha

data = {'a': ['asd.fgh', 'abcd.efg', '123.456', '123.456.789']}
df = pd.DataFrame(data=data)

for i in range(len(df)):
    df.loc[i, 'c'], df.loc[i, 'd'] = str(df.loc[i, 'a']).split(sep='.', maxsplit=1)

print(df)

#              #              a     c        d
# # 0      asd.fgh   asd      fgh
# # 1     abcd.efg  abcd      efg
# 2      123.456   123      456
# 3  123.456.789   123  456.789


2022-09-20 15:18

str.split + expand=True is the simplest.

Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import pandas as pd

>>> df = pd.DataFrame({"a":[ "abc,def", "eig,esi", "333,ee1"]})
>>> df
         A
0  abc,def
1  eig,esi
2  333,ee1
>>> df["a"].str.split(",")
0    [abc, def]
1    [eig, esi]
2    [333, ee1]
Name: a, dtype: object
>>> df["a"].str.split(",", expand=True)
     0    1
0  abc  def
1  eig  esi
2  333  ee1


>>> df[["a1", "a2"]] = df["a"].str.split(",", expand=True)
>>> df
         a   a1   a2
0  abc,def  abc  def
1  eig,esi  eig  esi
2  333,ee1  333  ee1
>>> 


2022-09-20 15:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.