2

I want to take input in the form of lists and join them into strings. How I can store the output as a dataframe column?

The input X is a dataframe and the column name is des:

X['des'] =
[5, 13]
[L32MM, 4MM, 2]
[724027, 40]
[58, 60MM, 36MM, 0, 36, 3]
[8.5, 45MM]
[5.0MM, 44MM]
[10]

This is my code:

def clean_text():
    for i in range(len(X)):
        str1 = " " 
        print(str1.join(X['des'][i]))

m = clean_text
m()

And here is my output, but how I can make it as a dataframe?

5 13
L32MM 4MM 2
724027 40
58 60MM 36MM 0 36 3
8.5 45MM
5.0MM 44MM
10
tdy
  • 36,675
  • 19
  • 86
  • 83
  • You can be inspired by the [answer](https://stackoverflow.com/a/70124869/8704180) I had given recently. It is the way we apply some function (in your case cleaning text) on a column of data frame then save it to another. – meti Nov 28 '21 at 09:49
  • Rather than giving the output of your function without details on its behavior, please provide an example input of your data, the matching expected output, and a short description of the logic to read it. – mozway Nov 28 '21 at 09:59
  • @mozway please check now – Shrikant Shejwal_IND Nov 28 '21 at 10:21

1 Answers1

1

Note that iterating in pandas is an antipattern. Whenever possible, use DataFrame and Series methods to operate on entire columns at once.


Series.str.join (recommended)

X['joined'] = X['des'].str.join(' ')

Output:

                          des               joined
0                     [5, 13]                 5 13
1             [L32MM, 4MM, 2]          L32MM 4MM 2
2                [724027, 40]            724027 40
3  [58, 60MM, 36MM, 0, 36, 3]  58 60MM 36MM 0 36 3
4                 [8.5, 45MM]             8.5 45MM
5               [5.0MM, 44MM]           5.0MM 44MM
6                        [10]                   10

Loop (not recommended)

Output:

                          des                 loop           itertuples             iterrows
0                     [5, 13]                 5 13                 5 13                 5 13
1             [L32MM, 4MM, 2]          L32MM 4MM 2          L32MM 4MM 2          L32MM 4MM 2
2                [724027, 40]            724027 40            724027 40            724027 40
3  [58, 60MM, 36MM, 0, 36, 3]  58 60MM 36MM 0 36 3  58 60MM 36MM 0 36 3  58 60MM 36MM 0 36 3
4                 [8.5, 45MM]             8.5 45MM             8.5 45MM             8.5 45MM
5               [5.0MM, 44MM]           5.0MM 44MM           5.0MM 44MM           5.0MM 44MM
6                        [10]                   10                   10                   10
tdy
  • 36,675
  • 19
  • 86
  • 83