简体   繁体   English

如何将pandas dataframe列连接到可迭代列表?

[英]How to concatenate pandas dataframe columns into iterable lists?

I'm working with a pandas dataframe with about 200 columns. 我正在使用大约200列的pandas数据帧。 Columns 31-73 look something like this: 第31-73列看起来像这样:

31   32   33
NaN  NaN  Z
X    NaN  Z
NaN  NaN  NaN
NaN  Y    Z

What I hope to return is a new column that looks (something) like this: 我希望返回的是一个看起来像这样的新列:

new_col
[Z]
[X,Z]
[]
[Y,Z]

I'm close, but not quite there. 我很亲密,但并不完全。 This code: 这段代码:

data['new_col'] = data.ix[:, 30:73].fillna('').apply(lambda row: ','.join(map(str, row)), axis=1)

returns this: 返回:

new_col
,,Z
,X,,Z
,,,
,,Y,Z

How can I exclude unnecessary delimiters from the new concatenated list? 如何从新的连接列表中排除不必要的分隔符?

You seem to have an errant value Nan which I'm assuming is NaN , anyway this should work: 你似乎有一个错误的价值Nan ,我假设是NaN ,无论如何这应该工作:

In [24]:
df.apply(lambda x: [','.join(x.dropna())], axis=1)

Out[24]:
0      [Z]
1    [X,Z]
2       []
3    [Y,Z]
dtype: object

So in your case: 所以在你的情况下:

data['new_col'] = data.apply(lambda x: [','.join(x.dropna())], axis=1)

should work. 应该管用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM