只需1即可更改4列

时间:2018-11-20 13:02:37

标签: python dataframe multiple-columns melt

我正在尝试将4个conunms从我的DataFrame转换为唯一列。

我有以下DataFrame:

    doggo   floofer pupper  puppo
0   None    None    None    None
1   None    None    None    None
2   None    None    None    None
3   None    None    None    None
4   None    None    None    None
5   None    None    None    None
6   None    None    None    None
7   None    None    None    None
8   None    None    None    None
9   doggo   None    None    None
10  None    None    None    None
11  None    None    None    None
12  None    None    None    puppo
13  None    None    None    None
14  None    None    None    puppo

我想要一个唯一的列,其中填充了值'None','doggo','floofer','pupper','puppo'。

我尝试使用Melt函数没有成功。

我的实际代码:

melt = pd.melt(melt, id_vars=['doggo', 'floofer', 'pupper', 'puppo'], var_name='classification')

有帮助吗?

编辑

完整的解决方案下面(注释以葡萄牙语):

#criar uma cópia do DataFrame para não comprometer o DataFrame original
df = twitter_archive.copy()

#Apagar os valores None 
df = df.replace('None', '')

#criar e preencher a coluna classification com as informações das colunas doggo, floofer, pupper e puppo
df['classification'] = (df['doggo'].fillna('') + df['floofer'].fillna('') + df['pupper'].fillna('') + df['puppo'].fillna('')).replace('', np.nan)

#Dropar todas as colunas e deixar somente a classification
df = df.drop(columns=['in_reply_to_status_id', 'in_reply_to_user_id', 'timestamp', 'source', 'text', 'retweeted_status_id', 'retweeted_status_user_id', 'retweeted_status_timestamp', 'expanded_urls', 'rating_numerator', 'rating_denominator', 'name', 'doggo','floofer', 'pupper', 'puppo'])

#Acrescentar a coluna classification no DataFrame twitter_archive e remover as colunas doggo, floofer, pupper e puppo
twitter_archive = pd.merge(twitter_archive, df, on= 'tweet_id')
twitter_archive = twitter_archive.drop(columns=['doggo', 'floofer', 'pupper', 'puppo'])

2 个答案:

答案 0 :(得分:2)

一种快速而肮脏的方法:

df['classification'] = (df['doggo'].fillna('') + df['floofer'].fillna('') + df['pupper'].fillna('') + df['puppo'].fillna('')).replace('', np.nan)

答案 1 :(得分:0)

只取最大。每个字符串都大于无。假设您的输入(每行)是唯一的。以下应该可以工作

d = {"col1": [None, "x", None], "col2": ["y",None, None]}
x = pd.DataFrame(d)
x["col3"] = x[["col1", "col2"]].max(axis=1)

输出:

   col1  col2  col3
0  None     y     y
1     x  None     x
2  None  None  None