df
date price vol
0 2010-01-04 34,57282657 2,600,000
1 2010-01-04 123,900 2,600,000
2 2010-01-04 353,6789738 2,600,000
有没有一种方法可以从通用代码中的1或2(此处为日期)以外的所有列中删除逗号? (我实际上有20列。)
预期输出:
date price vol
0 2010-01-04 3457282657 2600000
1 2010-01-04 123900 2600000
2 2010-01-04 3536789738 2600000
答案 0 :(得分:4)
在数据框的列上使用DataFrame.replace
,但不包括exclude
列表中的列:
exclude = ['date']
c = df.columns.difference(exclude)
df[c] = df[c].replace(',', '', regex=True)
结果:
date price vol
0 2010-01-04 3457282657 2600000
1 2010-01-04 123900 2600000
2 2010-01-04 3536789738 2600000
答案 1 :(得分:1)
您可以使用.iloc
和.replace
并传递regex=True
来替换特定的列 positions 。例如,将第一列之后的所有内容替换为df.iloc[:,1:]
的样子如下:
import pandas as pd
df = pd.read_clipboard()
df.iloc[:,1:] = df.iloc[:,1:].replace(',','', regex=True)
df
Out[19]:
date price vol
0 2010-01-04 3457282657 2600000
1 2010-01-04 123900 2600000
2 2010-01-04 3536789738 2600000
答案 2 :(得分:0)
为简单起见,您可以将列转换为int类型。
df.price.astype(int)
df.vol.astype(int)
答案 3 :(得分:0)
最好的imo解决方案是在您的读取语句中使用thousands=','
,即
pd.read_csv(...,thousands=',')
from io import StringIO
d = """ date price vol
0 2010-01-04 34,57282657 2,600,000
1 2010-01-04 123,900 2,600,000
2 2010-01-04 353,6789738 2,600,000"""
df = pd.read_csv(StringIO(d),sep='\s+',thousands=',')
print(df)
date price vol
0 2010-01-04 3457282657 2600000
1 2010-01-04 123900 2600000
2 2010-01-04 3536789738 2600000
print(df.dtypes)
date object
price int64
vol int64
dtype: object
我们可以使用filter
和replace
@Shubham Sharma的帽子提示以进行正则表达式更正。
df[df.filter(regex="^(?!date)").columns] = df.filter(regex="^(?!date)")\
.replace(",", "", regex=True)
^(?!date)
不包括日期列-您可以使用按位或符号|
^(?!date|vol)
print(df)
date price vol
0 2010-01-04 3457282657 2600000
1 2010-01-04 123900 2600000
2 2010-01-04 3536789738 2600000