熊猫:根据现有数据框中列的名称和数据创建新的数据框

时间:2020-07-04 15:43:18

标签: python pandas dataframe dataset data-science

基本上,对于每个 non-nan 行,我都希望该行的列名的第二部分(在逗号之后)并将其存储在new_df中-新的数据框(具有与在现有数据帧(df)中其列的第一部分(逗号前)命名的列下的现有数据帧中的非Nan值。

抱歉,如果我变得笨拙,我会用词。

我的代码

new_df = pd.DataFrame()

for i in range(0, len(df)):
    for j in cols[:3]:
        if df.loc[i, j] != "nan":
            col = j
            x = col.split(',')[1]
            y = col.split(',')[0].split(',')[0]
            new_df[y][i] = x
        else:
            pass

在上面的代码中,我仅在政治部分进行了测试,但没有成功,并且不确定如何在整个数据帧中做到这一点。

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

import numpy as np
import pandas as pd

df = pd.DataFrame({'Politics, Very Interested': [np.nan, np.nan, np.nan, 1],
                    'Politics, Not Interested': [np.nan, 1, 1, np.nan]})

col_labels = ['']*len(df.columns)
for c, col in enumerate(df.columns):
    col_name, val = col.split(',')
    df.loc[df[col].notna(), col] = val
    col_labels[c] = col_name

df.columns = col_labels

print(df)

为您提供我创建的数据框的子集

           Politics         Politics
0               NaN              NaN
1               NaN   Not Interested
2               NaN   Not Interested
3   Very Interested              NaN

编辑: 如果现在要合并具有相同名称的列并删除NaN,则必须首先用空字符串替换NaN,然后使用groupby对具有相同名称的列进行分组,最后使用{{1 }}与apply组合:

np.max

以我的示例为您提供的

df.fillna('', inplace=True)
df = df.groupby(df.columns, axis=1).apply(np.max, axis=1)

然后,如果需要,可以用 Politics 0 1 Not Interested 2 Not Interested 3 Very Interested 替换空字符串。