我有一个由多个列组成的数据帧,这些列的单元格可能包含字符串,也可能不包含字符串。例如:
import numpy as np
import pandas as pd
df = pd.DataFrame({'A':['asfe','eseg','eesg','4dsf','','hdt','gase','gex','gsges','hhbr'],
'B':['','bdb','htsdg','','rdshg','th','tjf','','',''],
'C':['hrd','jyf','sef','hdsr','','','','','hdts','aseg'],
'D':['','','hdts','afse','nfd','','htf','','',''],
'E':['','','','','jftd','','','','jfdt','']})
…看起来像:
A B C D E
0 asfe hrd
1 eseg bdb jyf
2 eesg htsdg sef hdts
3 4dsf hdsr afse
4 rdshg nfd jftd
5 hdt th
6 gase tjf htf
7 gex
8 gsges hdts jfdt
9 hhbr aseg
我想创建一个列,该列包含一个二进制表示,表示该列是否包含字符串;例如,第一行将表示为10100。你知道吗
我唯一能想到的办法是:
这是我创建的代码:
scratchdf = pd.DataFrame().reindex_like(df)
for col in df.columns.values:
scratchdf[col] = df[col].str.contains(r'\w+',regex = True).astype(int)
scratchdf['bin'] = scratchdf['A'].astype(str) + \
scratchdf['B'].astype(str) + \
scratchdf['C'].astype(str) + \
scratchdf['D'].astype(str) + \
scratchdf['E'].astype(str)
df = df.join(scratchdf['bin'])
…生成最终数据帧:
A B C D E bin
0 asfe hrd 10100
1 eseg bdb jyf 11100
2 eesg htsdg sef hdts 11110
3 4dsf hdsr afse 10110
4 rdshg nfd jftd 01011
5 hdt th 11000
6 gase tjf htf 11010
7 gex 10000
8 gsges hdts jfdt 10101
9 hhbr aseg 10100
这是可行的,但似乎有点浪费(尤其是对于大数据帧)。有没有一种方法可以直接创建二进制表示列,而不需要创建临时数据帧?你知道吗
选中空字符串或首先转换为
bool
,然后转换为int
,str
,最后转换为join
或sum
:时间安排:
可以使用以下事实:空字符串对应于False,非空字符串对应于True。因此,将字符串dataframe转换为bool将给出一个true和false的数据帧。将此重铸为int会将true转换为1,将false转换为0,然后只需跨行应用联接操作:
结果:
编辑:刚刚实现另一个用户发布了基本相同的东西(也修复了复制错误)
下面是使用生成器的另一种方法:
这比我的机器上的类型转换方法慢大约3倍,但是应该使用 最小内存。你知道吗
方法1
方法2
方法2将
\n
追加到numpy数组的末尾然后调用
tostring
和decode
。删除最后一个“\n”,然后按“\n”拆分。你知道吗方法3(使用
view
参考:numpy array of chars to string)时间安排:
耶斯雷尔的复制实验
相关问题 更多 >
编程相关推荐