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)
agg+ dropna+ str.join.
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 :)
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
, , - , , . , ', ', NaN :
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
df.stack().groupby(level=1).apply(','.join).to_frame().T Out[163]: col1 col2 col3 0 3 1,7 8
:
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
Source: https://habr.com/ru/post/1695011/More articles:Почему stat не может использовать имя из readdir? - cI get the default value 0 when I try to insert a value into an array after sorting I - javaКак управлять аутентификацией профиля пользователя в getstream.io? - node.jsMultiple background highlighting in Chart.js - javascriptAuth users and profiles in getstream.io - getstream-ioAllowed - EOF value is always true, even if there is a record returned from VBA SQL - sqlEOF returns true even if I have a populated record set in the first pos in ADO - vbaHow do I know where an exception can be thrown in my Haskell program? - httpСохранение тега, открытого после применения closeAll после того, как я нажимаю на содержимое в теге - javascriptКак избежать n + 1 запросов в EF Core 2.1? - c#All Articles