熊猫连接数据框和序列

时间:2018-09-18 21:57:52

标签: python pandas dataframe concatenation

我有一个主数据帧sdb,我想在for循环中通过它,从其某些列中获取唯一值,并将这些值连接到新的输出数据帧df中。一旦每个索引只有唯一的值,索引就会有所不同。看到下面我要去的地方:

tbl = ''
i = 1
df = pd.DataFrame()

for col in sdb.columns:
    tbl = 'e_{}'.format(i)
    uni = sdb[col].nunique()
    if uni <= 25:
        tbl = pd.DataFrame(sdb[col].drop_duplicates())
        tbl.reset_index(drop=True)

    df = pd.concat([df, tbl], axis=1)

此代码一直工作到到达最后一行并抛出错误:无法连接类型为“”的对象;仅pd.Series,pd.DataFrame ... 这对我来说还不清楚,因为当我同时在tbl和df上执行.info()时,它们都显示为数据帧。 任何谢意

1 个答案:

答案 0 :(得分:1)

以下是说明情况的示例:

space_index

输出:

import pandas as pd

tbl = ''
sdb = pd.DataFrame(
           {'A': [1, 2, 3, 4, 5],
            'B': [1, 2, 3, 4, 4],
            'C': [1, 2, 3, 3, 3],
            'D': [1, 2, 2, 2, 2]},
            index=[0, 1, 2, 3, 4])

df  = pd.DataFrame()
print(sdb)
print('\n')

for col in sdb.columns:
  uni = sdb[col].nunique()
  if uni <= 3:
    tbl = pd.DataFrame(sdb[col].drop_duplicates())
    tbl.reset_index(drop=True)

    df = pd.concat([df, tbl], axis=1)

print(df)
相关问题