python - 如何切换列中的单词?

标签 python python-3.x pandas

我收到了一个 .csv 文件,并要求我使用 pandas 来回答一些问题。 在其中一个问题中,它要求找到三个最受欢迎的名字。但要求打印出名字,然后打印出姓氏。我知道该怎么做,但我的名字和姓氏之间怎么能有空格,例如“John Smith”而不是“JohnSmith”。

我的代码是这样的:

works['ConductorName'] = works['ConductorName'].str.replace(r'(.+),\s+(.+)',r'\2\1')
results = works['ConductorName'].value_counts()

display(results.to_frame().head(3))

这将打印数据如下:

AlanGilbert  695
JoshuaGersen 45
RobFisher    35

最佳答案

试试这个:

来源 DF:

In [38]: df
Out[38]:
  ConductorName  val
0   AlanGilbert  695
1  JoshuaGersen   45
2     RobFisher   35

解决方案:

In [39]: df.ConductorName.str.replace(r'([a-z])([A-Z])', r'\1 \2')
Out[39]:
0     Alan Gilbert
1    Joshua Gersen
2       Rob Fisher
Name: ConductorName, dtype: object

但是您可以简单地更改代码,如下所示:

works['ConductorName'] = works['ConductorName'].str.replace(r'(.+),\s+(.+)',r'\2 \1')
#                                                                              _^_

关于python - 如何切换列中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43558555/

相关文章:

python - 如何计算numpy数组中元素的频率?

python - 保存从数组中删除的数字的位置

python - 代码大战。整数 : Recreation One. 我有错误 "Execution Timed Out"

python - 位置权限弹出窗口

python - Pandas read_sql_query 将整数列转换为 float

python - Scipy.optimize.l_bfgs_b : why does it compute several time the same function value?

python - 使用下拉菜单外键 : IntegrityError XXX_id may not be NULL 保存表单集

python-3.x - 使用模拟获取应用的函数输入数据框

python - 使用带有列表与范围的 .ix 索引的意外结果

python - 如何用Python获取最近的工作日?