两个 Pandas 列的字符串连接
- 2024-12-31 08:37:00
- admin 原创
- 108
问题描述:
我有以下追随者DataFrame
:
from pandas import *
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
它看起来像这样:
bar foo
0 1 a
1 2 b
2 3 c
现在我想要的是类似的东西:
bar
0 1 is a
1 2 is b
2 3 is c
我怎样才能做到这一点? 我尝试了以下方法:
df['foo'] = '%s is %s' % (df['bar'], df['foo'])
但它给了我一个错误的结果:
>>>print df.ix[0]
bar a
foo 0 a
1 b
2 c
Name: bar is 0 1
1 2
2
Name: 0
抱歉,问了一个愚蠢的问题,但是这个pandas:在 DataFrame 中合并两列对我没有帮助。
解决方案 1:
df['bar'] = df.bar.map(str) + " is " + df.foo
解决方案 2:
这个问题已经得到解答了,但我相信最好将一些以前未讨论过的有用方法混合在一起,并在性能方面比较迄今为止提出的所有方法。
以下是针对此问题的一些有用的解决方案,按性能的递增顺序排列。
DataFrame.agg
这是一种str.format
基于简单的方法。
df['baz'] = df.agg('{0[bar]} is {0[foo]}'.format, axis=1)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
您还可以在此处使用 f 字符串格式:
df['baz'] = df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
char.array
-based 连接
将列转换为连接形式chararrays
,然后将它们相加。
a = np.char.array(df['bar'].values)
b = np.char.array(df['foo'].values)
df['baz'] = (a + b' is ' + b).astype(str)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
列表理解zip
我不能夸大熊猫中列表推导式被低估的程度。
df['baz'] = [str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])]
或者,使用str.join
concat(也将更好地扩展):
df['baz'] = [
' '.join([str(x), 'is', y]) for x, y in zip(df['bar'], df['foo'])]
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
列表推导在字符串操作方面表现出色,因为字符串操作本质上很难矢量化,而大多数 pandas“矢量化”函数基本上都是循环的包装器。我在Pandas 的 For 循环 - 我应该何时关注?中详细讨论了这个主题。一般来说,如果您不必担心索引对齐,请在处理字符串和正则表达式操作时使用列表推导。
上面的列表 comp 默认不处理 NaN。但是,如果您需要处理它,您可以随时编写一个包装 try-except 的函数。
def try_concat(x, y):
try:
return str(x) + ' is ' + y
except (ValueError, TypeError):
return np.nan
df['baz'] = [try_concat(x, y) for x, y in zip(df['bar'], df['foo'])]
perfplot
性能测量
使用perfplot生成的图表。以下是完整的代码清单。
功能
def brenbarn(df): return df.assign(baz=df.bar.map(str) + " is " + df.foo) def danielvelkov(df): return df.assign(baz=df.apply( lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)) def chrimuelle(df): return df.assign( baz=df['bar'].astype(str).str.cat(df['foo'].values, sep=' is ')) def vladimiryashin(df): return df.assign(baz=df.astype(str).apply(lambda x: ' is '.join(x), axis=1)) def erickfis(df): return df.assign( baz=df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)) def cs1_format(df): return df.assign(baz=df.agg('{0[bar]} is {0[foo]}'.format, axis=1)) def cs1_fstrings(df): return df.assign(baz=df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)) def cs2(df): a = np.char.array(df['bar'].values) b = np.char.array(df['foo'].values) return df.assign(baz=(a + b' is ' + b).astype(str)) def cs3(df): return df.assign( baz=[str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])])
解决方案 3:
代码中的问题是您想要对每一行应用该操作。但是,您编写的方式会获取整个“bar”和“foo”列,将它们转换为字符串并返回一个大字符串。您可以这样编写:
df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
它比其他答案更长,但更通用(可以与非字符串的值一起使用)。
解决方案 4:
您还可以使用
df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ')
解决方案 5:
df.astype(str).apply(lambda x: ' is '.join(x), axis=1)
0 1 is a
1 2 is b
2 3 is c
dtype: object
解决方案 6:
series.str.cat
是解决这个问题最灵活的方法:
为了 df = pd.DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
df.foo.str.cat(df.bar.astype(str), sep=' is ')
>>> 0 a is 1
1 b is 2
2 c is 3
Name: foo, dtype: object
或者
df.bar.astype(str).str.cat(df.foo, sep=' is ')
>>> 0 1 is a
1 2 is b
2 3 is c
Name: bar, dtype: object
与(用于连接单个系列中包含的列表)不同.join()
,此方法用于连接两个系列。它还允许您NaN
根据需要忽略或替换值。
解决方案 7:
10年过去了,没有人提出最简单、最直观的方法,比这10年提出的所有例子快50%。
df.bar.astype(str) + ' is ' + df.foo
解决方案 8:
@DanielVelkov 答案是正确的,但使用字符串文字更快:
# Daniel's
%timeit df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
## 963 µs ± 157 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# String literals - python 3
%timeit df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
## 849 µs ± 4.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
解决方案 9:
我认为对于任意数量的列,最简洁的解决方案是这个答案的简短版本:
df.astype(str).apply(' is '.join, axis=1)
您可以使用 来删去另外两个字符df.agg()
,但是速度较慢:
df.astype(str).agg(' is '.join, axis=1)
解决方案 10:
我遇到了一个特殊情况,我的数据框中有 10^11 行,在这种情况下,所提出的解决方案都不合适。我使用了类别,当唯一字符串的数量不是太大时,这在所有情况下都应该可以正常工作。这可以在 R 软件中使用 XxY 和因子轻松完成,但我找不到任何其他方法在 python 中完成(我是 python 新手)。如果有人知道实现这一点的地方,我会很高兴知道。
def Create_Interaction_var(df,Varnames):
'''
:df data frame
:list of 2 column names, say "X" and "Y".
The two columns should be strings or categories
convert strings columns to categories
Add a column with the "interaction of X and Y" : X x Y, with name
"Interaction-X_Y"
'''
df.loc[:, Varnames[0]] = df.loc[:, Varnames[0]].astype("category")
df.loc[:, Varnames[1]] = df.loc[:, Varnames[1]].astype("category")
CatVar = "Interaction-" + "-".join(Varnames)
Var0Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[0]].cat.categories)).rename(columns={0 : "code0",1 : "name0"})
Var1Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[1]].cat.categories)).rename(columns={0 : "code1",1 : "name1"})
NbLevels=len(Var0Levels)
names = pd.DataFrame(list(itertools.product(dict(enumerate(df.loc[:,Varnames[0]].cat.categories)),
dict(enumerate(df.loc[:,Varnames[1]].cat.categories)))),
columns=['code0', 'code1']).merge(Var0Levels,on="code0").merge(Var1Levels,on="code1")
names=names.assign(Interaction=[str(x) + '_' + y for x, y in zip(names["name0"], names["name1"])])
names["code01"]=names["code0"] + NbLevels*names["code1"]
df.loc[:,CatVar]=df.loc[:,Varnames[0]].cat.codes+NbLevels*df.loc[:,Varnames[1]].cat.codes
df.loc[:, CatVar]= df[[CatVar]].replace(names.set_index("code01")[["Interaction"]].to_dict()['Interaction'])[CatVar]
df.loc[:, CatVar] = df.loc[:, CatVar].astype("category")
return df
解决方案 11:
from pandas import *
x = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
x
x['bar'] = x.bar.astype("str") + " " + "is" + " " + x.foo
x.drop(['foo'], axis=1)