我试图将从函数返回的序列连接到数据帧,但我不希望列重复。我怎样才能做到这一点?完整的数据集大约有100k行,大约有100个子集(定义在一个带掩码的循环中),因此希望有一个计算快速的解决方案。使用Python 3.7
示例
import pandas as pd
def myfcn(row, data, val):
z1 = row['y'] + val
z2 = row['x']*row['y']
return pd.Series(
{'fancy_column_name1': z1,
'fancy_column_name2': z2/val},
name=row.name
)
col1 = [1, 1.5, 3.1, 3.4, 2, -1]
col2 = [1, -3, 2, 8, 2.5, -1.3]
df = pd.DataFrame(list(zip(col1, col2)), columns=['x', 'y'])
display(df)
### In the real case, this is all in a loop with many subsets that
### are created with masks & specific criteria; this is
### simplified here
df_subset = df.iloc[[0,2,3]]
#display(df_subset)
out = df_subset.apply(myfcn, axis=1, args=(df_subset, 100))
df = pd.concat([df, out], axis=1)
df_subset2 = df.iloc[[5]]
out = df_subset2.apply(myfcn, axis=1, args=(df_subset2, 250))
df = pd.concat([df, out], axis=1)
display(df)
这是父数据帧“df”
这是当前输出
这是想要的输出
如何删除重复的列名,将数据折叠到同一列中?我想保留号码,而不是南号。永远不会有一个实例,其中一行中要保留多个数字,但可能有一个实例中没有数字(因此,请保留NaN)
只需将
df = pd.concat([df, out], axis=1)
替换为-更多详情here
订单未保留的原因是
out
只有2列。这些首先取代了NAN的值。因此,他们成为第一批。您可以在out之前插入空白的x和y来解决此问题-将此添加到循环中,让我知道您的列顺序现在是否已修复
一起计算子设置,然后将这些列附加在一起,然后合并到主数据框中。我稍微修改了您的代码:
输出:
相关问题 更多 >
编程相关推荐