简体   繁体   English

如何删除 Pandas Dataframe 列中所有值的字符串的最后一个字符?

[英]How to delete the last character of a string for all values in a Pandas Dataframe column?

For example if this is my Dataframe (all values are str type):例如,如果这是我的 Dataframe(所有值都是 str 类型):

    Random  Random2  Random3    
0   WNNX01  319845   6109100104 
1   WNNX01  319850   6205200002 
2   WNNX01  319865   6403990062 
3   WNNX01  319868   6109901000
4   WNNX01  319888   6204422000

How do I get rid of the last character in all values for "Random3" column?如何摆脱“Random3”列的所有值中的最后一个字符? I want the result to look like this:我希望结果如下所示:

    Random  Random2  Random3    
0   WNNX01  319845   610910010  
1   WNNX01  319850   620520000  
2   WNNX01  319865   640399006  
3   WNNX01  319868   610990100
4   WNNX01  319888   620442200

This will work but it takes forever with millions of rows (been running for 15mins still not done):这将起作用,但它需要数百万行(运行了 15 分钟仍未完成):

for i in range(len(df)):
    df['Random3'][i] = df['Random3'][i][:-1]

What's a better way?有什么更好的方法?

Try this.尝试这个。 It would be more efficient than your code.它会比你的代码更有效。

df['Random3'] = df['Random3'].astype(str).str.slice(start = 0, stop = -1)

Because the code makes 'Random3' column string, you can change the type using astype function as follows.由于代码生成了“Random3”列字符串,因此您可以使用 astype function 更改类型,如下所示。

df['Random3'] = df['Random3'].astype(int)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何删除熊猫数据框的最后一列数据 - How to delete the last column of data of a pandas dataframe Pandas:删除特定字符重复4次的dataframe列中特定字符(最后一个特定字符)之前的所有字符 - Pandas: Remove all characters before a specific character (last specific character) in a dataframe column that specific character is repeated 4 times 删除DataFrame的所有最后一个字符串 - delete all last string of DataFrame 如何编辑 pandas dataframe 中列的所有值? - How to edit all values of a column in a pandas dataframe? 评估 pandas 中列的最后一个字符 dataframe - evaluate last character of column in pandas dataframe 如何更改 Pandas 数据框的字符串列中的值? - How to change values in a string column of a Pandas dataframe? 如何删除熊猫数据框的最后一列中的第一个值,然后删除其余的最后一行? - How to delete first value in the last column of a pandas dataframe and then delete the remaining last row? 删除列中所有值的子字符串 pandas - delete a sub-string for all values in a column pandas 如果所有值都是某个字符串,则删除 pandas dataframe 中的列 - Removing a column in a pandas dataframe if all the values are a certain string 对于 pandas 中的列中的所有值,如何从字符串中删除字符并将 rest 转换为 integer 或十进制? - How to remove a character from a string and convert the rest into integer or decimal, for all values in a column in pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM