【问题标题】:Python Pandas concatenate strings and numbers into one stringPython Pandas 将字符串和数字连接成一个字符串
【发布时间】:2017-10-25 08:21:38
【问题描述】:

我正在使用 pandas 数据框并尝试将多个字符串和数字连接成一个字符串。

这行得通

df1 = pd.DataFrame({'Col1': ['a', 'b', 'c'], 'Col2': ['a', 'b', 'c']})
df1.apply(lambda x: ', '.join(x), axis=1)

0    a, a
1    b, b
2    c, c

我怎样才能像 df1 一样进行这项工作?

df2 = pd.DataFrame({'Col1': ['a', 'b', 1], 'Col2': ['a', 'b', 1]})
df2.apply(lambda x: ', '.join(x), axis=1)

TypeError: ('sequence item 0: expected str instance, int found', 'occurred at index 2')

【问题讨论】:

  • 尝试将lambda x: ', '.join(x)更改为lambda x: ', '.join(str(x))

标签: python string pandas concatenation


【解决方案1】:

考虑数据框df

np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(10, size=(3, 3)),
    columns=list('abc')
)

print(df)

   a  b  c
0  0  2  7
1  3  8  7
2  0  6  8

您可以在lambda 之前使用astype(str)

df.astype(str).apply(', '.join, 1)

0    0, 2, 7
1    3, 8, 7
2    0, 6, 8
dtype: object

使用理解

pd.Series([', '.join(l) for l in df.values.astype(str).tolist()], df.index)

0    0, 2, 7
1    3, 8, 7
2    0, 6, 8
dtype: object

【讨论】:

  • 这太棒了!谢谢
【解决方案2】:
In [75]: df2
Out[75]:
  Col1 Col2 Col3
0    a    a    x
1    b    b    y
2    1    1    2

In [76]: df2.astype(str).add(', ').sum(1).str[:-2]
Out[76]:
0    a, a, x
1    b, b, y
2    1, 1, 2
dtype: object

【讨论】:

    【解决方案3】:

    您必须将列类型转换为字符串。

    import pandas as pd
    df2 = pd.DataFrame({'Col1': ['a', 'b', 1], 'Col2': ['a', 'b', 1]})
    df2.apply(lambda x: ', '.join(x.astype('str')), axis=1)
    

    【讨论】:

      猜你喜欢
      • 2017-05-14
      • 2012-02-02
      • 2013-05-15
      • 2015-05-02
      • 1970-01-01
      • 2022-12-17
      • 2014-03-15
      • 2015-06-18
      • 2014-04-19
      相关资源
      最近更新 更多