在pandas中,将数据框的每一行转换为字符串,并将其作为列分配给另一个数据集。

问题描述 投票:0回答:1

我有一个数据集。

id   name   address   phone   email
123  abc    123 abc   12345   [email protected]
456  cbs    456 cbs   67890   [email protected]
758  nbc    789 nbc   11121   [email protected]

我想创建一个新的数据集 保留前两列(id和name)和第三列,其中有一个字符串,是地址,电话和电子邮件的组合。换句话说,我需要它看起来像这样。

id   name   meta_str
123  abc    '123 abc   12345   [email protected]'
456  cbs    '456 cbs   67890   [email protected]'
758  nbc    '789 nbc   11121   [email protected]'

这是我的代码

df_transformed = df[['id','name']]
df_meta = df[['address','phone','email']]
df_meta_str = df_meta.iloc[:].to_string(header=False, index=False)
df_transformed['meta_str'] = df_meta_str

但我得到的结果是:

id   name   meta_str
123  abc    '123 abc   12345   [email protected]'
456  cbs    '123 abc   12345   [email protected]'
758  nbc    '123 abc   12345   [email protected]'

我想问题在于df_meta_str把所有行的数据都组合成一个大字符串。

有什么办法可以实现在单独的行上有一个单独的字符串呢?

python-3.x pandas string data-conversion
1个回答
3
投票

您可以使用 pd.Series.cat 这里。

df['meta_str'] = df['address'].str.cat(df[['phone','email']].astype(str),sep=' ')
df.drop(columns='address')

   id   name   meta_str
0  123  abc    123 abc 12345 [email protected]
1  456  cbs    456 cbs 67890 [email protected]
2  758  nbc    789 nbc 11121 [email protected]


2
投票

您可以使用简单的 str concatenation:

df['meta_str'] = df.address + ' ' + df.phone.astype(str) + ' ' + df.email 

df.drop(['address','phone','email'], 1, inplace=True)

产出:

id   name   meta_str
123  abc    123 abc 12345 [email protected]
456  cbs    456 cbs 67890 [email protected]
758  nbc    789 nbc 11121 [email protected]

使用 df.apply 方法。

df['meta_str'] = df[['address','phone','email']].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)

1
投票

我会做

df['meta_str']=df.loc[:,'address':].astype(str).agg(' '.join,1)
0    123abc 12345 [email protected]
1    456cbs 67890 [email protected]
2    789nbc 11121 [email protected]
dtype: object
© www.soinside.com 2019 - 2024. All rights reserved.