How to combine the values ​​of all rows in a data frame into one row without changing columns?

I have a data input that looks like this:

  col1 col2 col3
0    3    1  NaN
1  NaN    7    8

How to collapse all rows when concatenating data in rows with ', '?

Required data frame output:

  col1  col2 col3
0    3  1, 7    8

Example input code:

import pandas as pd
import numpy as np


d = {'col1': ["3", np.nan], 'col2': ["1", "7"], 'col3': [np.nan, "8"]}
df = pd.DataFrame(data=d)
+4
source share
5 answers

agg+ dropna+ str.join.

df.agg(lambda x: ', '.join(x.dropna())).to_frame().T

  col1  col2 col3
0    3  1, 7    8

There are other solutions, my peers will find them for you :)

+6
source
pd.DataFrame(
    [[
        ', '.join(map(str, map(int, filter(pd.notna, c))))
        for c in zip(*df.values)
    ]], columns=df.columns
)

  col1  col2 col3
0    3  1, 7    8
+5
source

, , - , , . , ', ', NaN :

new_df = pd.DataFrame(columns=df.columns)

for col in df.columns:
    new_df.loc[0, col] = ', '.join(df[col].dropna().tolist())

>>> new_df
  col1  col2 col3
0    3  1, 7    8
+4

df.stack().groupby(level=1).apply(','.join).to_frame().T
Out[163]: 
  col1 col2 col3
0    3  1,7    8
+4

:

In [156]: pd.DataFrame([[df[c].dropna().astype(int).astype(str).str.cat(sep=', ') 
                         for c in df]], 
                       columns=df.columns)
Out[156]:
  col1  col2 col3
0    3  1, 7    8
+3
source

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


All Articles