gpt4 book ai didi

python - 按 dtype 为字符串和数字的条件删除列

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:12 25 4
gpt4 key购买 nike

我有以下数据(列数可能会有所不同):

    NAME    ID  POTENTIAL_VOTERS    VOTES   SPOILT_VOTES    LEGAL_VOTES אמת ג   ודעם    ז   ... נץ  ע   פה  ף   ףץ  קנ  קץ  רק  שס  voter_turnout
0 תל אביב - יפו 5000 403338 263205 1860 261345 89567 2628 8488 9 ... 34 132 30241 105 124 2667 2906 209 10189 0.647955
1 ירושלים 3000 385888 258879 3593 255286 24696 53948 3148 10 ... 54 215 10752 37 148 1619 18330 121 30579 0.661555
2 חיפה 4000 243274 151318 1758 149560 37805 4894 12363 24 ... 16 103 16826 40 87 1596 1648 142 3342 0.614780
3 ראשון לציון 8300 195958 138998 1188 137810 31492 924 86 8 ... 16 5 19953 26 68 1821 2258 121 4095 0.703263
4 פתח תקווה 7900 177367 125633 1223 124410 22103 4810 85 8 ... 14 9 14661 15 65 1224 3227 74 6946 0.701427
5 אשדוד 70 170193 115145 1942 113203 9694 11132 33 7 ... 14 10 8841 26 74 1322 4180 80 11923 0.665145
6 נתניה 7400 168914 106738 1270 105468 14575 2921 65 5 ... 14 9 11035 40 63 1089 3177 103 8319 0.624389

当我尝试按总和条件删除列时(总和小于 40000 我不需要此列),使用此代码:

df.drop([col for col, val in df.sum().iteritems() if val < 40000], axis=1, inplace=True)

我收到以下错误:

TypeError: '<' not supported between instances of 'str' and 'int'

我假设这是因为某些列不是整数(因为有文本)。知道如何解决这个问题吗?

最佳答案

这里的问题是 sum 将连接所有字符串,您需要过滤 df 以仅选择数字数据类型,然后过滤它们:

In[27]:
df = pd.DataFrame({'a': list('abcd'), 'b':np.random.randn(4), 'c':np.arange(4)})
df

Out[27]:
a b c
0 a -0.053771 0
1 b 0.124416 1
2 c -2.024073 2
3 d -2.541324 3

我们可以使用 select_dtypes 只选择数字类型并传递 np.number

In[28]:
df1 = df.select_dtypes([np.number])
df1

Out[28]:
b c
0 -0.053771 0
1 0.124416 1
2 -2.024073 2
3 -2.541324 3

现在我们可以过滤列了:

In[29]:
df1.loc[:,df1.sum() > 1]

Out[29]:
c
0 0
1 1
2 2
3 3

您可以看到 sum 正在返回连接的字符串

In[30]:
df.sum()

Out[30]:
a abcd
b -4.49475
c 6
dtype: object

关于python - 按 dtype 为字符串和数字的条件删除列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48703279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com