nat*_*nat 66 python string numpy dataframe pandas
我有以下内容DataFrame:
from pandas import *
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
Run Code Online (Sandbox Code Playgroud)
它看起来像这样:
bar foo
0 1 a
1 2 b
2 3 c
Run Code Online (Sandbox Code Playgroud)
现在我希望有类似的东西:
bar
0 1 is a
1 2 is b
2 3 is c
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我尝试了以下方法:
df['foo'] = '%s is %s' % (df['bar'], df['foo'])
Run Code Online (Sandbox Code Playgroud)
但它给了我一个错误的结果:
>>>print df.ix[0]
bar a
foo 0 a
1 b
2 c
Name: bar is 0 1
1 2
2
Name: 0
Run Code Online (Sandbox Code Playgroud)
抱歉有一个愚蠢的问题,但是这只熊猫:在DataFrame中合并两列对我没用.
Dan*_*kov 40
代码中的问题是您希望在每一行上应用操作.你编写它的方式虽然需要整个'bar'和'foo'列,将它们转换为字符串并返回一个大字符串.你可以这样写:
df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
Run Code Online (Sandbox Code Playgroud)
它比其他答案更长,但更通用(可以使用非字符串的值).
cs9*_*s95 38
这个问题已经得到了回答,但是我相信最好将一些以前没有讨论过的有用方法混入混合物中,并比较到目前为止提出的所有方法的性能。
以下是按性能递增顺序解决此问题的一些有用方法。
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
Run Code Online (Sandbox Code Playgroud)
您还可以在此处使用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
Run Code Online (Sandbox Code Playgroud)
char.array基于串联将这些列转换为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
Run Code Online (Sandbox Code Playgroud)
zip我不能高估熊猫的列表理解程度。
df['baz'] = [str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])]
Run Code Online (Sandbox Code Playgroud)
或者,使用str.joinconcat(也可以更好地扩展):
df['baz'] = [
' '.join([str(x), 'is', y]) for x, y in zip(df['bar'], df['foo'])]
Run Code Online (Sandbox Code Playgroud)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
Run Code Online (Sandbox Code Playgroud)
列表理解在字符串操作方面表现出色,因为字符串操作本来就很难向量化,并且大多数熊猫“向量化”函数基本上都是循环的包装器。我在For循环与熊猫中写了很多有关该主题的文章-什么时候应该关心?。通常,如果您不必担心索引对齐,请在处理字符串和正则表达式操作时使用列表理解。
默认情况下,上面的列表组件不处理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'])]
Run Code Online (Sandbox Code Playgroud)
perfplot 绩效评估功能
Run Code Online (Sandbox Code Playgroud)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'])])
chr*_*lle 12
你也可以用
df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ')
Run Code Online (Sandbox Code Playgroud)
10 年过去了,没有人提出最简单直观的方法,比这 10 年来提出的所有示例快 50%。
df.bar.astype(str) + ' is ' + df.foo
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
或者
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
Run Code Online (Sandbox Code Playgroud)
与.join()(用于连接包含在单个系列中的列表)不同,此方法用于将 2 个系列连接在一起。它还允许您根据需要忽略或替换NaN值。
| 归档时间: |
|
| 查看次数: |
66183 次 |
| 最近记录: |