我想创建一个指标变量,它将传播到具有与指标相同的客户周期值对的所有行.具体来说,如果baz是yes,我希望同一客户和期间电子邮件的所有行显示我的指标.
df
Customer Period Question Score
A 1 foo 2
A 1 bar 3
A 1 baz yes
A 1 biz 1
B 1 bar 2
B 1 baz no
B 1 qux 3
A 2 foo 5
A 2 baz yes
B 2 baz yes
B 2 biz 2
Run Code Online (Sandbox Code Playgroud)
我试过了
df['Indicator'] = np.where(
(df.Question.str.contains('baz') & (df.Score == 'yes')),
1, 0)
Run Code Online (Sandbox Code Playgroud)
返回
Customer Period Question Score Indicator
A 1 foo 2 0
A 1 bar 3 …Run Code Online (Sandbox Code Playgroud) 我试图在sns条形图中按组显示相对百分比以及总频率.我比较的两个组的大小差别很大,这就是我在下面的函数中按组显示百分比的原因.
以下是我创建的示例数据框的语法,该数据框与目标分类变量('item')中的数据('groups')具有相似的相对组大小.'rand'只是我用来制作df的变量.
# import pandas and seaborn
import pandas as pd
import seaborn as sns
import numpy as np
# create dataframe
foobar = pd.DataFrame(np.random.randn(100, 3), columns=('groups', 'item', 'rand'))
# get relative groupsizes
for row, val in enumerate(foobar.rand) :
if val > -1.2 :
foobar.loc[row, 'groups'] = 'A'
else:
foobar.loc[row, 'groups'] = 'B'
# assign categories that I am comparing graphically
if row < 20:
foobar.loc[row, 'item'] = 'Z'
elif row < 40:
foobar.loc[row, 'item'] = 'Y'
elif row < …Run Code Online (Sandbox Code Playgroud) 我有一个多D型系列pd.Series一样[100, 50, 0, foo, bar, baz]
当我跑步时 pd.Series.str.isnumeric()
我懂了 [NaN, NaN, NaN, False, False, False]
为什么会这样呢?它不应该返回True本系列的前三个吗?
我正在尝试使用两列重新整形数据框:ID和分类,以便每个唯一的分类值都有一列.
这是我有的:
ID Animal
foo cat
foo dog
bar cat
baz cat
biz dog
biz cow
biz dog
Run Code Online (Sandbox Code Playgroud)
这就是我想要的:
ID cat dog cow
foo 1 1 0
bar 1 0 0
baz 1 0 0
biz 0 1 2
Run Code Online (Sandbox Code Playgroud)
我试过了:
df.groupby(by='ID').count()
Run Code Online (Sandbox Code Playgroud)
这使:
Index Animal
foo 2
bar 1
baz 1
biz 3
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
df.pivot_table(values='Animal')
df.stack(level='Animal')
Run Code Online (Sandbox Code Playgroud)
前者抛出DataError:没有要聚合的数值类型,后者抛出KeyError:Level Animal必须与name相同(None)
我在 pd.DataFrame 中有几列,其中小数点分隔小时和分钟(例如,3.15 = 3 小时 15 分钟)。有没有一种快速的方法来转换它以便数据被识别为 hm ?pandas 时间序列文档似乎不适用于我的情况。我没有也不想附上任何日期。
我试过:
# create df
hour_min = pd.DataFrame({'a': [4.5, 2.3, 3.17],
'b': [2.12, 1.13, 9.13],
'c': [8.23, 9.14, 7.45]})
# convert to hours
hour_min.astype('timedelta64[h]')
Run Code Online (Sandbox Code Playgroud)
这使
a b c
0 04:00:00 02:00:00 08:00:00
1 02:00:00 01:00:00 09:00:00
2 03:00:00 09:00:00 07:00:00
Run Code Online (Sandbox Code Playgroud)
但我想要
a b c
0 04:50 02:12 08:23
1 02:30 01:13 09:14
2 03:17 09:13 07:45
Run Code Online (Sandbox Code Playgroud)
我还需要添加/减去列值 1.32 + 1.32 = 3.04 的以下类型的结果