【问题标题】:How to add a something to a string in the first column of my csv?如何在我的 csv 第一列的字符串中添加一些东西?
【发布时间】:2020-02-23 18:02:26
【问题描述】:
我的 csv 中有 3 列。在我的 csv 的第一列中,我想在 python 列中所有条目的开头添加数字“1”。
我不知道该怎么做?
例如
当前列数据:5678967745
我想在它的开头添加一个 1,所以它的开头是这样的“15678967745”。
我想对列中的所有条目执行此操作。
【问题讨论】:
标签:
python
pandas
csv
python-textprocessing
【解决方案1】:
假设您有一个数据框df 和一个名为Datetime 的列,它是一个int。要修改避免for loop 的值,您可以在列上使用map。你可以试试:
df['Datetime'] = df['Datetime'].map(lambda x: int("1"+str(x))
您首先将列中的每个值转换为string,然后将它们连接起来1。最后,新号码再次转换为int。
希望对你有帮助。
【解决方案2】:
您可以将您的数字转换为字符串,将“1”添加为字符串,然后将整个内容转换回数字,假设这很重要。
numbers_as_strings = df["numbers"].astype(str)
numbers_with_1 = "1"+numbers_as_strings
numbers_as_numeric = pd.to_numeric(numbers_with_1)
df["numbers"] = numbers_as_numeric