我有兴趣生成一个由 pandas 行和列数据组成的字符串。给定以下 pandas 数据框,我只对从具有正值的列生成字符串感兴趣
index A B C
1 0 1 2
2 0 0 3
3 0 0 0
4 1 0 0
我想创建一个新列,附加一个字符串,列出一行中哪些列为正。然后我会删除数据来自的所有行:
index Positives
1 B-1, C-2
2 C-3
4 A-1
最佳答案
这是使用 pd.DataFrame.apply
+ pd.Series.apply
的一种方法:
df = pd.DataFrame([[1, 0, 1, 2], [2, 0, 0, 3], [3, 0, 0, 0], [4, 1, 0, 0]],
columns=['index', 'A', 'B', 'C'])
def formatter(x):
x = x[x > 0]
return (x.index[1:].astype(str) + '-' + x[1:].astype(str))
df['Positives'] = df.apply(formatter, axis=1).apply(', '.join)
print(df)
index A B C Positives
0 1 0 1 2 B-1, C-2
1 2 0 0 3 C-3
2 3 0 0 0
3 4 1 0 0 A-1
如果您需要过滤掉零长度字符串,您可以利用空字符串通过 bool
计算为 False
的事实:
res = df[df['Positives'].astype(bool)]
print(res)
index A B C Positives
0 1 0 1 2 B-1, C-2
1 2 0 0 3 C-3
3 4 1 0 0 A-1
关于python - 从 pandas 列和行数据创建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50915875/