Python 每天字符串的平均值和总和
我有一个3列的数据框。我正在使用python/pandasPython 每天字符串的平均值和总和,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个3列的数据框。我正在使用python/pandas date id my_value1 my_value2 0 31.07.20 128909 0.098333 positive 1 31.07.20 128914 0.136364 positive 3 31.07.20 853124 -0.025000 negative 4 30
date id my_value1 my_value2
0 31.07.20 128909 0.098333 positive
1 31.07.20 128914 0.136364 positive
3 31.07.20 853124 -0.025000 negative
4 30.07.20 123456 -1.000000 neutral
...
第一列包含日期(可以解析为任何其他形式),日期从20年2月6日到20年7月31日,但缺少一些天。正如你所见,每天都会出现好几次
列my_value1包含一个介于1和-1之间的浮点数
my_value2列包含字符串“positive”、“negative”或“neutral”
我想要的是一个新的数据框,其中包含每天“my_value1”的平均值和“my_value2”的每个值的总和,如下所示:
date average_value1 sum_positive sum_negative sum_neutral
0 31.07.20 0.1 1532 2153 5321
1 30.07.20 0.2 2153 5321 1532
3 29.07.20 -0.3 1234 1234 1234
...
谢谢你的帮助 下面是我将要做的:
from io import StringIO
import pandas as pd
# read data
df = pd.read_csv(StringIO(""" date id my_value1 my_value2
0 31.07.20 128909 0.098333 positive
1 31.07.20 128914 0.136364 positive
3 31.07.20 853124 -0.025000 negative
4 30.07.20 123456 -1.000000 neutral
"""), sep='\s+')
df.date = pd.to_datetime(df.date)
df.set_index('date', inplace=True)
# obtain daily average
df_avg = df.resample('D').my_value1.mean().to_frame('average')
# obtain the counts
df_cnt = df.resample('D').my_value2.value_counts()
df_cnt = df_cnt.to_frame()
df_cnt = df_cnt.unstack()
df_cnt = df_cnt.droplevel(level=0, axis=1)
# join the two dataframes
df_avg.join(df_cnt)
# The desired output
average negative neutral positive
date
2020-07-30 -1.000000 NaN 1.0 NaN
2020-07-31 0.069899 1.0 NaN 2.0
试试这个:
tmp1 = df.groupby('date')['my_value1'].mean().to_frame('average_value1')
tmp2 = (
df.groupby(['date', 'my_value2'])
['my_value1'].sum()
.unstack()
[['positive', 'negative', 'neutral']]
)
tmp2.columns = 'sum_' + tmp2.columns
result = tmp1.join(tmp2)
如果原始数据帧的索引不重要,您可以这样做
encoded_df = pd.get_dummies(df, prefix="", prefix_sep="", columns=["my_value2"])
output = encoded_df.groupby("date").agg(
average_value1 = pd.NamedAgg("my_value1", "mean"),
sum_positive = pd.NamedAgg("positive", "sum"),
sum_negative = pd.NamedAgg("negative", "sum"),
sum_neutral = pd.NamedAgg("neutral", "sum")
).reset_index()
输出:
date average_value1 sum_positive sum_negative sum_neutral
0 30.07.20 -1.000000 0 0 1
1 31.07.20 0.069899 2 1 0
看起来它可以工作,但该列不包含作为数字的总和,而是包含一个长字符串,例如“positivepositivepositivepositivepositivepositivepositive…”。你知道一个快速解决方法吗?我把它改成大写,因为它在我的数据中实际上是大写的。但所有其他列名都适合。